为什么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"
是不是比字符串格式化操作灵活很多?
查看documentation page 上的更多示例,以比较% 操作和.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
# 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.'
有没有人知道什么是特定于一种字符串格式化操作的功能,而不是另一种?听到它可能会很有趣。