python格式化函式format

2022-06-08 08:21:10 字數 796 閱讀 3536

格式(填充)對齊,可以格式化任何物件,包括字串,數值等

#format函式會return字串結果,但不會列印

# 1. 格式化填充單個物件

print( format(text, '=>20s') )

# '*****====hello world'

# =:符號填充

# > 內容右對齊, < 左對齊, ^ 居中

# 20:字串總長度控制

# s:以字串型別列印輸出,f:浮點數,,d:整數

# 2.同時格式化多個物件

' '.format('hello', 'world')

# "hello world"

# format作用於單個字串**,串內可以格式化多個資料,多個資料分別用{}包裹

# 內部:後放**填充位置引數,資料截斷進度,填充符號,字元總長度控制引數等;

# : 前沒什麼用,隨便寫不寫都行

"{} {}".format("hello", "world") # 不設定指定位置,預設按順序對應輸出

# 'hello world'

# 3.格式化數字

x = 1.2345

format(x, '>10')

# ' 1.2345'

format(x, '^10.2f')

# ' 1.23 '

# 舊的格式化輸出方法%(僅能格式化字串型別)

import math

# " %"中的 %變數佔位符 會被 後面%符號 後的數值填充

python筆記 字串格式化函式format

自python2.6開始,新增了一種格式化字串的函式str.format 通過 和 來代替 通過位置 in 1 format cqk 20 out 1 cqk,20 in 2 format cqk 20 out 2 cqk,20 in 3 format cqk 20 out 3 20,cqk,20 ...

Python格式化函式 format

格式 模板字串 format 逗號分隔的引數 format 逗號分隔的引數 引數序號 0,1,2,3 引導符 格式控制標記 用來控制引數顯示時的格式,包括 填充 對齊 寬度 format hello world 不設定指定位置,按預設順序 hello world format hello world...

python 格式化和format格式化

格式 name flags width precision typecode name 可選,用於選擇指定的key flags 可選,可提供的值有 右對齊,整數前加正號,負數前加負號 左對齊,正數錢無符號,負數前加負號 空格 右對齊 正數前加空格,負數前加負號 0 右對齊,正數前無符號,負數前加負號...