'{0} in {1}'.format(unicode(self.author,'utf-8'), unicode(self.publication,'utf-8'))
不再鼓励使用%格式化字符串。
This method of string formatting is the new standard in Python 3.0, and should be preferred to the % formatting described in String Formatting Operations in new code.
Given format % values, % conversion specifications in format are replaced with zero or more elements of values. The effect is similar to the using sprintf() in the C language.
If format requires a single argument, values may be a single non-tuple object. Otherwise, values must be a tuple with exactly the number of items specified by the format string, or a single mapping object (for example, a dictionary).
Perform a string formatting operation. The string on which this method is called can contain literal text or replacement fields delimited by braces {}. Each replacement field contains either the numeric index of a positional argument, or the name of a keyword argument. Returns a copy of the string where each replacement field is replaced with the string value of the corresponding argument.
This method is the new standard in Python 3.0, and should be preferred to % formatting.
>>> '%s for %s' % ("tit", "tat")
tit for tat
>>> '{} and {}'.format("chicken", "waffles")
chicken and waffles
>>> '%(last)s, %(first)s %(last)s' % {'first': "James", 'last': "Bond"}
Bond, James Bond
>>> '{last}, {first} {last}'.format(first="James", last="Bond")
Bond, James Bond
马克·西德的回答是对的——你需要提供一个元组。
但是,从Python 2.6开始,您可以使用^{} 而不是
%
:不再鼓励使用
%
格式化字符串。关于多参数的元组/映射对象
format
以下是文档的摘录:
参考文献
在
上str.format
而不是%
替代
%
运算符的新方法是使用str.format
。以下是文档摘要:参考文献
示例
下面是一些用法示例:
另见
如果使用多个参数,则必须在元组中(请注意额外的括号):
正如EOL所指出的,
unicode()
函数通常假定ascii编码为默认值,因此如果您有非ascii字符,则显式传递编码更安全:从Python 3.0开始,最好使用^{} 语法:
相关问题 更多 >
编程相关推荐