使用 %
# 三个参数, 字符串%s, 整数%d, 浮点数%f (%.2f 保留2位小数)
name = 'wss'
age = 22
stature = 1.75
s = "my name is %s, my age is %d, my stature is %.2f" % (name, age, stature)
print(s)
结果: my name is wss, my age is 22, my stature is 1.75
使用format方法
name = 'wss'
age = 22
stature = 1.75
# 通过index
s = 'my name is {0}, age is {1}, stature is {2:.3f}'.format(name, age, stature)
# 通过key
s = 'my name is {nm}, age is {ag}, stature is {sta:.3f}'.format(nm=name, ag=age, sta=stature)
print(s)
结果: my name is wss, age is 22, stature is 1.750
动态指定浮点数的保留位数
stature = 1.75
for i in range(3):
s = "my stature is %.*f" % (i+1, stature)
print(s)
结果:
my stature is 1.8
my stature is 1.75
my stature is 1.750
使用字典
dct = {'name': 'wss', 'age': 22, 'stature': 1.75}
# %
s = 'my name is %(name)s, age is %(age)d, stature is %(stature).2f' % dct
# format
s = 'my name is {name}, age is {age}, stature is {stature:.2f}'.format_map(dct)