顺序写入:{}
a= '{} ---- {} ----- {}' . format ( 'abort' , 'bank' , 'cat' )
数字指定传入的参数:{2}
a= '{2} ---- {0} ----- {2}' . format ( 'abort' , 'bank' , 'cat' )
指定传入的参数、长度:{2:5s}
a= '{2:5s} ---- {2:5s} ----- {2:10s} ----' . format ( 'abort' , 'bank' , 'cat' )
传入元组:(*tuple_var)
b= ( 'abort' , 'bank' , 'cat' , 'def' )
a= '{} ---- {} ----- {}' . format ( * b)
传入元组2:(*tuple_var)
t= ( 111 , 444 )
h= 'x:{0[0]}---y:{0[1]}' . format ( t) x: 111 - - - y: 444
关键字参数:{key}
h= '--- a={a}--- b={b}' . format ( a= 111 , b= 222 , c= 333 )
传入字典:(**dict_var)
d= { 'a' : 111 , 'b' : 222 , 'c' : 333 }
h= '--- a={a}--- b={b}' . format ( ** d)
传入对象
c= 22 + 33j
h= 'real:{0.real}----imag:{0.imag}' . format ( c)
h= 'real:{a.real}----imag:{a.imag}' . format ( a= c)
左对齐,右对齐,居中
h= '{:<30}' . format ( 'left aligned' )
print ( h)
h= '{:>30}' . format ( 'right aligned' )
print ( h)
h= '{:^30}' . format ( 'centered' )
print ( h)
h= '{:*^30}' . format ( 'centered' )
print ( h)
正数前用加号或空格填充
h= '---{0:+f}----{0: f}---{0:f}---' . format ( 3.14 , - 3.14 )
其他进制:加#的区别
h= "int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}" . format ( 42 )
print ( h)
h= "int: {0:#d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}" . format ( 42 )
print ( h)
>> > "{:x}" . format ( 4275878544 )
'fedcba90'
>> > "{:#x}" . format ( 4275878544 )
'0xfedcba90'
>> > "{:20x}" . format ( 4275878544 )
' fedcba90'
>> > "{:#20x}" . format ( 4275878544 )
' 0xfedcba90'
千分符:,
h= '{:,}' . format ( 1234567890 )
限制小数位:.
h= 'Correct answers: {:.3%}' . format ( 9 / 11 )