Why format()
比更灵活%
字符串操作
我认为你真的应该坚持format()
的方法str
,因为它是格式化字符串的首选方式,并且将来可能会取代字符串格式化操作。
此外,它还有一些非常好的功能,还可以将基于位置的格式与基于关键字的格式相结合:
>>> 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"
是不是比字符串格式化操作灵活很多呢?
查看更多示例文档页 http://docs.python.org/library/string.html#format-examples用于比较%
运营和.format()
method.
比较基于元组的%
基于字典的字符串格式化
一般有三种调用方式%
字符串操作 (yes, three, not two) 像那样:
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
# some code goes here
>>> '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.'
还有其他人知道什么可能是特定于一种类型的字符串格式化操作的功能,而不是另一种类型的功能吗?听到这个可能会很有趣。