在Python中使用多个参数格式化字符串(例如,'%s。。。%s')

2024-05-20 22:50:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个看起来像'%s in %s'的字符串,我想知道如何分隔参数,使它们是两个不同的%s。我来自Java的想法是这样的:

'%s in %s' % unicode(self.author),  unicode(self.publication)

但这不起作用,所以它在Python中看起来怎么样?


Tags: 字符串inself参数unicodejavaauthorpublication
3条回答

马克·西德的回答是对的——你需要提供一个元组。

但是,从Python 2.6开始,您可以使用^{}而不是%

'{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.

关于多参数的元组/映射对象format

以下是文档的摘录:

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).

参考文献


str.format而不是%

替代%运算符的新方法是使用str.format。以下是文档摘要:

str.format(*args, **kwargs)

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

另见

如果使用多个参数,则必须在元组中(请注意额外的括号):

'%s in %s' % (unicode(self.author),  unicode(self.publication))

正如EOL所指出的,unicode()函数通常假定ascii编码为默认值,因此如果您有非ascii字符,则显式传递编码更安全:

'%s in %s' % (unicode(self.author,'utf-8'),  unicode(self.publication('utf-8')))

从Python 3.0开始,最好使用^{}语法:

'{0} in {1}'.format(unicode(self.author,'utf-8'),unicode(self.publication,'utf-8'))

相关问题 更多 >