python学习(10)—— 格式化python字符串

格式化字符串

Python用字符串的format()方法来格式化字符串。

具体用法如下,字符串中花括号 {} 的部分会被format传入的参数替代,传入的值可以是字符串,也可以是数字或者别的对象。

'{} {} {}'.format('a', 'b', 'c')
'a b c'

可以用数字指定传入参数的相对位置:

'{2} {1} {0}'.format('a', 'b', 'c')
'c b a'

还可以指定传入参数的名称:

'{color} {n} {x}'.format(n=10, x=1.5, color='blue')
'blue 10 1.5'

可以在一起混用:

'{color} {0} {x} {1}'.format(10, 'foo', x = 1.5, color='blue')
'blue 10 1.5 foo'

可以用{<field name>:<format>}指定格式:

from math import pi

'{0:10} {1:10d} {2:10.2f}'.format('foo', 5, 2 * pi)
'foo                 5       6.28'
from math import pi
# >靠右输出 <靠左输出 ^居中输出
'{0:>10} {1:^10d}{1:<10d} {2:10.2f}'.format('foo', 5, 10 ,2 * pi)  
'       foo     5     5               10.00'
x=1234567
format(x,',')
'1,234,567'

具体规则与C中相同。

也可以使用旧式的 % 方法进行格式化:

s = "some numbers:"
x = 1.34
y = 2
# 用百分号隔开,括号括起来
t = "%s %f, %d" % (s, x, y)
t
'some numbers: 1.340000, 2'

猜你喜欢

转载自blog.csdn.net/weixin_43763724/article/details/88764832