常用字符串格式化哪几种?

% 格式化字符串操作符

print 'hello %s and %s' % ('df', 'another df')

字典形式的字符串格式化方法

print 'hello %(first)s and %(second)s' % {'first': 'df', 'second': 'another df'}

字符串格式化(format)

(1) 使用位置参数

位置参数不受顺序约束,且可以为{},参数索引从0开始,format里填写{}对应的参数值。

>>> msg = "my name is {}, and age is {}"
>>> msg.format("hqs",22)
'my name is hqs, and age is 22'

(2) 使用关键字参数

关键字参数值要对得上,可用字典当关键字参数传入值,字典前加**即可

>>> hash = {'name':'john' , 'age': 23}
>>> msg = 'my name is {name}, and age is {age}'
>>> msg.format(**hash)
'my name is john,and age is 23'

(3) 填充与格式化 :填充字符[宽度]

>>> '{0:*<10}'.format(10)      # 左对齐
'10********'

发表评论

后才能评论