@[toc](Python String format())
format()方法的語法爲:
template.format(p0, p1, ..., k0=v0, k1=v1, ...)
其中p0,p1,…是位置參數,而k0,k1…是關鍵參數,有着v0,v1…得值
而且,template是混合了格式代碼和參數佔位符的代碼。
format()方法接受任意數量的參數。但是,又分爲兩類參數:
注意:參數列表從0開始。浮點數四捨五入。
例子1:
# default arguments print("Hello {}, your balance is {}.".format("Adam", 230.2346)) # positional arguments print("Hello {0}, your balance is {1}.".format("Adam", 230.2346)) # keyword arguments print("Hello {name}, your balance is {blc}.".format(name="Adam", blc=230.2346)) # mixed arguments print("Hello {0}, your balance is {blc}.".format("Adam", blc=230.2346))
注意:在混合參數的情況下,關鍵字參數必須始終跟隨位置參數
數字格式類型
例子2:
# integer arguments print("The number is:{:d}".format(123)) The number is: 123 # float arguments print("The float number is:{:f}".format(123.4567898)) The number is:123.456790 # octal, binary and hexadecimal format print("bin: {0:b}, oct: {0:o}, hex: {0:x}".format(12)) bin: 1100, oct: 14, hex: c
例子3:數字格式與填充的整數和浮點數
# integer numbers with minimum width print("{:5d}".format(12)) # width doesn't work for numbers longer than padding print("{:2d}".format(1234)) # padding for float numbers print("{:8.3f}".format(12.2346)) # integer numbers with minimum width filled with zeros print("{:05d}".format(12)) # padding for float numbers filled with zeros print("{:08.3f}".format(12.2346))
例子4:帶符號數字的數字格式
# show the + sign print("{:+f} {:+f}".format(12.23, -12.23)) # show the - sign only print("{:-f} {:-f}".format(12.23, -12.23)) # show space for + sign print("{: f} {: f}".format(12.23, -12.23)) +12.230000 -12.230000 12.230000 -12.230000 12.230000 -12.230000
帶對齊的數字格式化
操作符<、^、>和=用於在爲數字分配一定寬度時進行對齊。
< 左對齊
^ 居中對齊
> 右對齊
= 使符號打到最左端。
# integer numbers with right alignment print("{:5d}".format(12)) # float numbers with center alignment print("{:^10.3f}".format(12.2346)) # integer left alignment filled with zeros print("{:<05d}".format(12)) # float numbers with center alignment print("{:=8.3f}".format(-12.2346))
例子6:帶填充和對齊的字符串格式
# string padding with left alignment print("{:5}".format("cat")) # string padding with right alignment print("{:>5}".format("cat")) # string padding with center alignment print("{:^5}".format("cat")) # string padding with center alignment # and '*' padding character print("{:*^5}".format("cat"))
例子7:使用format()截斷字符串
# truncating strings to 3 letters print("{:.3}".format("caterpillar")) # truncating strings to 3 letters # and padding print("{:5.3}".format("caterpillar")) # truncating strings to 3 letters, # padding and center alignment print("{:^5.3}".format("caterpillar"))
例子8:使用format()格式化類成員
# define Person class class Person: age = 23 name = "Adam" # format age print("{p.name}'s age is: {p.age}".format(p=Person())) Adam's age is: 23
例子9:使用format()格式化字典成員
# define Person dictionary person = {'age': 23, 'name': 'Adam'} # format age print("{p[name]}'s age is: {p[age]}".format(p=person))
另一方法:
# define Person dictionary person = {'age': 23, 'name': 'Adam'} # format age print("{name}'s age is: {age}".format(**person))
**是一個格式參數(最小字段寬度)。
示例10:使用format()動態格式化
# dynamic string format template string = "{:{fill}{align}{width}}" # passing format codes as arguments print(string.format('cat', fill='*', align='^', width=5)) # dynamic float format template num = "{:{align}{width}.{precision}f}" # passing format codes as arguments print(num.format(123.236, align='<', width=8, precision=2))
使用format()的額外格式化選項
format()還支持特定於類型的格式化選項,比如datetime和複數格式。
format()在內部爲datetime調用_format__(),而format()訪問複數的屬性。
您可以輕鬆地重寫任何對象的_format__()方法來進行自定義格式化。
示例11:使用format()和覆蓋_format__()方法實現特定於類型的格式化
import datetime # datetime formatting date = datetime.datetime.now() print("It's now: {:%Y/%m/%d %H:%M:%S}".format(date)) # complex number formatting complexNumber = 1+2j print("Real part: {0.real} and Imaginary part: {0.imag}".format(complexNumber)) # custom __format__() method class Person: def __format__(self, format): if(format == 'age'): return '23' return 'None' print("Adam's age is: {:age}".format(Person()))
覆蓋__format__ ():
與datetime類似,您可以覆蓋您自己的用於自定義格式的_format__()方法,該方法在以{:age}訪問時返回年齡。
例子12:str()和 repr() 速記法,!r和!s用於format()
# __str__() and __repr__() shorthand !r and !s print("Quotes: {0!r}, Without Quotes: {0!s}".format("cat")) # __str__() and __repr__() implementation for class class Person: def __str__(self): return "STR" def __repr__(self): return "REPR" print("repr: {p!r}, str: {p!s}".format(p=Person())) Quotes: 'cat', Without Quotes: cat repr: REPR, str: STR