- format([‘alex’, ‘18’]),参数是数组加一个。
- format(**{‘name’: ‘alex’, ‘age’: '18‘}),参数是字典加两个星号。
默认字符串中的花括号与format的参数对应
tpl = 'I am a {}, age {}, name {}'.format('boy', 22, 'alex')
print(tpl)
# I am a boy, age 22, name alex
tpl = 'I am a {}, age {}, name {}'.format(*['boy', 22, 'alex'])
print(tpl)
# I am a boy, age 22, name alex
花括号传入数字的时候,代表后面参数的索引。
tpl = 'I am a {1}, age {0}, name {2}'.format('19', 'boy', 'alex')
print(tpl)
# I am a boy, age 19, name alex
tpl = 'I am a {1}, age {0}, name {2}'.format(*['19', 'boy', 'alex'])
print(tpl)
# I am a boy, age 19, name alex
花括号传入key值时与format参数的key值对应,无序
tpl = 'i am {name}, age {age}'.format(name = 'alex', age = '18')
print(tpl)
# i am alex, age 18
tpl = 'i am {name}, age {age}'.format(**{'name': 'alex', 'age': '18'})
print(tpl)
# i am alex, age 18
花括号传入n1[n2],n1表示对应format参数的第几个列表,n2表示列表元素索引
tpl = 'I am {0[0]}, age {1[2]}'.format(['alex', 'lupe'], [12, 18, 28])
print(tpl)
# I am alex, age 28
{?}表示字符串,{:d}表示十进制数字,{:f}表示精度6的浮点数
tpl = 'I am {:s}, age {:d} {:f}'.format('alex', 18, 12.34567)
print(tpl)
# I am alex, age 18 12.345670
tpl = 'I am {:s}, age {:d} {:f}'.format(*['alex', 18, 12.34567])
print(tpl)
# I am alex, age 18 12.345670
tpl = 'I am {name:s}, age {age:d}'.format(name = 'alex', age = 22)
print(tpl)
# I am alex, age 22
tpl = 'I am {name:s}, age {age:d}'.format(**{'name': 'alex', 'age': 22})
print(tpl)
# I am alex, age 22
{:b}二进制表示, {?}八进制表示, {:d}十进制表示, {:x}十六进制小写, {:X}十六进制大写, {:%}百分数表示
tpl = 'Numbers: {:b} {:o} {:d} {:x} {:X} {:%}'.format(15, 15, 15, 15, 15, 1.234567)
print(tpl)
# Numbers: 1111 17 15 f F 123.456700%