Python使用format函数和字典参数格式化字符串

对比不同的格式化方法

>>> s
'my name is {name}, aged {age}'
>>> dic
{'age': 30, 'name': 'vito'}
>>> sf1 = s.format(**dic)
>>> sf1
'my name is vito, aged 30'
>>> sf2 = s.format(name=dic['name'], age=dic['age'])
>>> sf2
'my name is vito, aged 30'
>>> sf3 = 'my name is %(name)s, aged %(age)d' % dic
>>> sf3
'my name is vito, aged 30'
>>> sf4 = 'my name is {1}, aged {0}'.format(30, 'vito')
>>> sf4
'my name is vito, aged 30'

你可能感兴趣的:(python)