format()
方法用于返回指定值的格式化表示形式。它由格式說明符處理,并將格式化的字符串插入字符串的占位符中。占位符可以用數字索引{0}、命名索引{price}甚至空的{ 0 }來表示。的格式()類似于‘String format’方法,兩種方法都調用一個對象的__format__()
方法。
**format(value[, format_spec])** #Where value can be a integer, float or binary format.
格式()參數:
這個函數有兩個參數:在這個格式中,規格可以是
[[填充]對齊][符號][#][0][寬度][,][。精度][類型]
其中,選項為 填充::=任意字符 對齊::= " < " | " > " | "=" | "^" 符號::= "+" | "-" | " " 寬度::=整數 精度::=整數 類型::= " b " | " c " | " d " | " e " | " e " | " f " | " f " | " g " | " g " | " n " | " o " | " s "
參數 | 描述 | 必需/可選 |
---|---|---|
價值 | 需要格式化的值 | 需要 |
格式 _ 規格 | 值應該如何格式化的規范。 | 需要 |
格式()返回值
| 投入 | 返回值 | | 格式規范。 | 格式化表示 |
Python 中format()
方法的示例
示例 1:格式為()的數字格式
# d, f and b are type
# integer
print(format(123, "d"))
# float arguments
print(format(123.4567898, "f"))
# binary format
print(format(12, "b"))
輸出:
123
123.456790
1100
示例 2:帶有填充、對齊、符號、寬度、精度和類型()的數字格式
# integer
print(format(1234, "*>+7,d"))
# float number
print(format(123.4567, "^-09.3f"))
輸出:
*+1,234
0123.4570
示例 3:通過覆蓋__format__()
來使用__format__()
# custom __format__() method
class Person:
def __format__(self, format):
if(format == 'age'):
return '23'
return 'None'
print(format(Person(), "age"))
輸出:
23