0%

Python格式化输出

Python格式化输出

格式化输出字符串

用法一:

与%s类似,不同指出是将%s换乘了‘{ }’大括号,调用时依然需要按照顺序对应

1
2
3
4
5
6
7
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
"""

用法二:

通过{n}方式来指定接收参数的位置,将调用时传入的参数按照位置进行传入。相比%s可以减少参数的个数,实现了参数的复用

1
2
3
4
5
6
7
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
"""