@[toc](Python String format())
文法
format()方法的文法為:
其中p0,p1,…是位置參數,而k0,k1…是關鍵參數,有着v0,v1…得值
而且,template是混合了格式代碼和參數占位符的代碼。
String format()參數
format()方法接受任意數量的參數。但是,又分為兩類參數:
- 位置參數-可以使用大括号{index}内的參數索引通路的參數清單
- 關鍵字參數——key=value類型的參數清單,可以使用大括号{key}内的key of parameter通路
String format()如何工作
注意:參數清單從0開始。浮點數四舍五入。
使用format()進行基本格式化
例子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))
注意:在混合參數的情況下,關鍵字參數必須始終跟随位置參數
數字格式類型
- d Decimal integer 十進制
- c Corresponding Unicode character 對應Unicode自u發
- b Binary format 二進制格式
- o Octal format 八進制
- x Hexadecimal format (lower case) 十六進制
- X Hexadecimal format (upper case) 十六進制
- n Same as ‘d’. Except it uses current locale setting for number separator
- e Exponential notation. (lowercase e) 指數
- E Exponential notation (uppercase E) 指數
- f Displays fixed point number (Default: 6) 顯示固定小數位數(預設6)
- F Same as ‘f’. Except displays ‘inf’ as ‘INF’ and ‘nan’ as ‘NAN’
- g General format. Rounds number to p significant digits. (Default precision: 6)
- G Same as ‘g’. Except switches to ‘E’ if the number is large. 除了轉化為E
- % Percentage. Multiples by 100 and puts % at the end. 百分比
例子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