1. Basic usage
>>> print('{} {}'.format('hello','world'))
hello world
>>> print('{1} {1} and {0}'.format('hello','world'))
world world and hello
>>> print('{a} {tom} {a}'.format(tom='hello',a='world')) #可用关键字
world hello world
>>> Hi = { 'hello', 'world'}
>>>print( 'X: {0[0]}; Y: {0[1]}'.format(Hi))#通过下标匹配
'X: hello; Y: world'
>>> Hi = {'a': 'hello', 'b': 'world'}
>>> print('X: {0[a]}; Y: {0[b]}'.format(Hi)) #通过key匹配
'X: hello; Y: world'
>>> print('{0:10s} and {0:>10s} and {1:^10s}'.format('hello','world'))
hello and hello and world
# {:10s} 取10位左对齐 {:>10s} 取10位右对齐 {:^10s} 取10位中间对齐
2.2. 多种格式化
>>> print('{0:+f} is {0:>10.1f}'.format(1.23)) # 取1位小数,右对齐,取10位
+1.230000 is 1.2
>>>print('{:,}'.format(1234567890)) #用“ , ”分割数字,千进位
'1,234,567,890'
>>>print('{:.2%}'.format(1/3)) #取小数点后2位的百分数
33.33%
'b' - 二进制。将数字以2为基数进行输出。exp:print('{0:b}'.format(3))
'c' - 字符。在打印之前将整数转换成对应的Unicode字符串。
'd' - 十进制整数。将数字以10为基数进行输出。
'o' - 八进制。将数字以8为基数进行输出。
'x' - 十六进制。将数字以16为基数进行输出,9以上的位数用小写字母。
'e' - 幂符号。用科学计数法打印数字。用'e'表示幂。
'g' - 一般格式。将数值以fixed-point格式输出。当数值特别大的时候,用幂形式打印。
'n' - 数字。当值为整数时和'd'相同,值为浮点数时和'g'相同。不同的是它会根据区域设置插入数字分隔符。
'%' - 百分数。将数值乘以100然后以fixed-point('f')格式打印,值后面会有一个百分号。
"!r"对应 repr();"!s"对应 str(); "!a"对应ascii()。
>>> "repr() shows quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2')
"repr() shows quotes: 'test1'; str() doesn't: test2" # 输出结果是一个带引号,一个不带
更多format详细参考:https://www.cnblogs.com/lovejh/p/9201219.html