s = "My name is {}, {} years old, and my hobby is {}" s1 = s.format('MMMMMQ', '25', 'watching TV') print(s1) """ output: My name is MMMMMQ, 25 years old, My hobby is watching TV """
s = "My name is {0}, {1} years old, and my name is still {0}" s1 = s.format('MMMMQ', '25', 'watching TV') print(s1) """ output: My name is MMMMQ, 25 years old, and my name is still MMMMQ """
用法三:
通过str{}方式来指定名字,调用时使用str='xxx',确定参数传入
1 2 3 4 5 6 7
s = "My name is {name}, {age} years old, and my hobby is {hobby}" s1 = s.format(age=25, hobby='watching TV', name='MMMMQ') print(s1) """ output: My name is MMMMQ, 25 years old, and my hobby is watching TV """
保留n位小数:
保留一个数字
1 2 3 4 5
print('This is a float number {:.2f}'.format(123.432423432)) """ output: This is a float number 123.43 """
保留两个数字
1 2 3 4 5
print('This are two float numbers {:.2f} and {:.4f}'.format(123.432423432, 0.321423423)) """ output: This are two float numbers 123.43 and 0.3214 """
保留数字和文字
1 2 3 4 5
print('This are two float numbers and a string {:.2f} , {:.4f} and {} '.format(123.432423432, 0.321423423, 'MMMMQ')) """ output: This are two float numbers and a string 123.43 , 0.3214 and MMMMQ """