为什么format()
比%
字符串操作更加灵活
我认为你应该坚持使用str
的format()
方法,因为它是格式化字符串的首选方式,并有可能在未来取代字符串格式化操作。
此外,它具有一些非常好的功能,可以将基于位置和关键字的格式化组合在一起:
>>> string = 'I will be {} years and {} months on {month} {day}'
>>> some_date = {'month': 'January', 'day': '1st'}
>>> diff = [3, 11] # years, months
>>> string.format(*diff, **some_date)
'I will be 3 years and 11 months on January 1st'
以下内容也可以正常工作:
>>> string = 'On {month} {day} it will be {1} months, {0} years'
>>> string.format(*diff, **some_date)
'On January 1st it will be 11 months, 3 years'
还有另外一个支持使用format()
的原因。因为它是一个方法,所以可以像以下示例中一样将其作为回调传递:
>>> data = [(1, 2), ('a', 'b'), (5, 'ABC')]
>>> formatter = 'First is "{0[0]}", then comes "{0[1]}"'.format
>>> for item in map(formatter, data):
print item
First is "1", then comes "2"
First is "a", then comes "b"
First is "5", then comes "ABC"
相比于字符串格式化操作,这种方法更加灵活,你可以在文档页面上查看更多例子,来对比百分号(%
)操作和.format()
方法的差异。
基于元组的 %
字符串格式化与基于字典的对比
通常有三种调用 %
字符串操作的方式(是的,三种而不是两种),就像这样:
base_string % values
它们的区别在于values
的类型(这是由base_string
的内容决定的):
如果它是一个tuple
,那么它们将一个接一个地被替换,按照它们在元组中出现的顺序进行替换,
>>> 'Three first values are: %f, %f and %f' % (3.14, 2.71, 1)
'Three first values are: 3.140000, 2.710000 and 1.000000'
它可以是一个 dict
(字典),然后根据关键词进行替换。>>> 'My name is %(name)s, I am %(age)s years old' % {'name':'John','age':98}
'My name is John, I am 98 years old'
如果base_string
只包含一个需要插入值的位置,那么它可以是单个值:
>>> 'This is a string: %s' % 'abc'
'This is a string: abc'
它们之间有明显的区别,这些方法不能结合使用(与format()
方法相反,该方法能够结合一些功能,如上所述)。
但是有一些东西只适用于基于字典的字符串格式化操作,并且在其余三种格式化操作类型中相对不可用。这就是能够以简单的方式将特定的指示符替换为实际变量名称的能力:
>>> name = 'John'
>>> surname = 'Smith'
>>> age = 87
>>> 'My name is %(surname)s, %(name)s %(surname)s. I am %(age)i.' % locals()
'My name is Smith, John Smith. I am 87.'
仅供参考:当然,上述内容可以轻松地通过使用format()
函数,并解包字典进行替换:
>>> 'My name is {surname}, {name} {surname}. I am {age}.'.format(**locals())
'My name is Smith, John Smith. I am 87.'
还有人知道哪种字符串格式化操作具有特定的功能,而另一种却没有吗?听起来很有趣。
format()
方法时,您无需在这两种参数传递方式之间进行选择 - 您可以同时使用两种方式(请参见我的答案)。 - Tadeck