天天看點

python字元串格式化—format

基本用法:
>>>"my name is {} and I am {} years old".format("junex",)
>>>'my name is junex and I am  years old'
           

“{}”相當于占位符,然後調用format()來指派。如果既想用format(),又想輸出“{}”怎麼辦?

>>>"hello {} and {{}}".format("world")
>>>'hello world and {}'
           
參數重排

可以用“{index}”的形式來對應format(param0,param1,…)的參數,注意index要從0開始:

>>>"apple is {0}, banana is {1}".format("red","yellow")
>>>'apple is red, banana is yellow'

>>>"apple is {1}, banana is {0}".format("red","yellow")
>>>'apple is yellow, banana is red'
           

也可以“{參數名}”的方式來對應參數,這樣的好處是代碼更易讀且不需要關心參數的順序:

>>>"my name is {name} and I am {age} years old".format(age=,name="junex")
>>>'my name is junex and I am  years old'
           
指定變量類型

這個時候就比較進階了,需要使用{field_name:conversion}的文法,field_name是來指明{}與參數的對應關系的,conversion用來格式化字元串。

#指明資料類型為浮點數
>>>"Today's temperature is {:f} degrees Celsius".format()
>>>'Today's temperature is  degrees Celsius'

#規定浮點數的精确度
>>>"Today's temperature is {:.3f} degrees Celsius".format()
>>>'Today's temperature is  degrees Celsius'
           

更多的使用參見官方文檔

填充

可以在:(冒号)後跟一個數字來表示參數的占據空間。

>>>"my name is {:20} and I am {:8} years old".format("junex", )
>>>"my name is junex                     and I am         18 years old".format("junex", )
           

可以看到字元串是預設左對齊的,數字是預設右對齊。

#左對齊
>>>"{:<10}".format("junex")
>>>'     junex'
#居中
>>>"{:^10}".format("junex")
>>>'  junex   '
#右對齊
>>>"{:>10}".format("junex")
>>>'junex     '
           

可以看到,python預設使用空格來填充,我們也可以使用自定義的字元來填充:

>>>"{:*^10}".format("junex")
>>>'**junex***'   
           

使用過程中遇到一個問題:

python字元串格式化—format
python字元串格式化—format

原因是當用0填充時,‘=’會預設使用,然而‘=’隻能用于數字。因為‘9’是字元串,是以會報上述錯誤。

可以使用定位符來解決解決:

python字元串格式化—format

參考How To Use String Formatters in Python 3 & 官方文檔