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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3395138/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 10:49:34  来源:igfitidea点击:

Using multiple arguments for string formatting in Python (e.g., '%s ... %s')

pythonstringsyntax

提问by Dean

I have a string that looks like '%s in %s'and I want to know how to seperate the arguments so that they are two different %s. My mind coming from Java came up with this:

我有一个看起来像的字符串,'%s in %s'我想知道如何分离参数,以便它们是两个不同的 %s。我从 Java 中想到了这个:

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

But this doesn't work so how does it look in Python?

但这不起作用,那么它在 Python 中的外观如何?

采纳答案by Mark Byers

Mark Cidade's answer is right - you need to supply a tuple.

Mark Cidade 的答案是正确的 - 您需要提供一个元组。

However from Python 2.6 onwards you can use formatinstead of %:

但是,从 Python 2.6 开始,您可以使用format代替%

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

Usage of %for formatting strings is no longer encouraged.

%不再鼓励使用for 格式化字符串。

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.

这种字符串格式化的方法是 Python 3.0 中的新标准,应该优先于新代码中的字符串格式化操作中描述的 % 格式化。

回答by Mark Cidade

If you're using more than one argument it has to be in a tuple (note the extra parentheses):

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

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

As EOL points out, the unicode()function usually assumes ascii encoding as a default, so if you have non-ASCII characters, it's safer to explicitly pass the encoding:

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

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

And as of Python 3.0, it's preferred to use the str.format()syntax instead:

从 Python 3.0 开始,最好使用以下str.format()语法:

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

回答by polygenelubricants

On a tuple/mapping object for multiple argument format

在多参数的元组/映射对象上 format

The following is excerpt from the documentation:

以下是文档的摘录:

Given format % values, %conversion specifications in formatare replaced with zero or more elements of values. The effect is similar to the using sprintf()in the C language.

If formatrequires 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 formatstring, or a single mapping object(for example, a dictionary).

给定format % values, 中的%转换规范format被替换为 的零个或多个元素values。效果类似于sprintf()在C语言中使用。

如果format需要单个参数,则值可能是单个非元组对象。否则,values 必须是一个元组,它的项数正好是formatstring指定的项数或者是单个映射对象(例如,字典)。

References

参考



On str.formatinstead of %

str.format而不是%

A newer alternative to %operator is to use str.format. Here's an excerpt from the documentation:

%运算符的更新替代方法是使用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.

str.format(*args, **kwargs)

执行字符串格式化操作。调用此方法的字符串可以包含用大括号分隔的文字文本或替换字段{}。每个替换字段包含位置参数的数字索引或关键字参数的名称。返回字符串的副本,其中每个替换字段都替换为相应参数的字符串值。

此方法是 Python 3.0 中的新标准,应该优先于%格式化.

References

参考



Examples

例子

Here are some usage examples:

以下是一些使用示例:

>>> '%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

See also

也可以看看

回答by John La Rooy

For python2 you can also do this

对于 python2 你也可以这样做

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

which is handy if you have a lot of arguments to substitute (particularly if you are doing internationalisation)

如果您有很多参数可以替代,这很方便(特别是如果您正在进行国际化)

Python2.6 onwards supports .format()

Python2.6 以上支持 .format()

'{author} in {publication}'.format(author=self.author,
                                   publication=self.publication)

回答by Eric O Lebigot

There is a significant problem with some of the answers posted so far: unicode()decodes from the default encoding, which is often ASCII; in fact, unicode()tries to make "sense" of the bytes it is given by converting them into characters. Thus, the following code, which is essentially what is recommended by previous answers, fails on my machine:

到目前为止发布的一些答案存在一个重大问题:unicode()从默认编码(通常是 ASCII)解码;事实上,unicode()试图通过将它们转换为字符来“理解”它给出的字节。因此,以下代码(基本上是先前答案所推荐的)在我的机器上失败:

# -*- coding: utf-8 -*-
author = 'éric'
print '{0}'.format(unicode(author))

gives:

给出:

Traceback (most recent call last):
  File "test.py", line 3, in <module>
    print '{0}'.format(unicode(author))
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128)

The failure comes from the fact that authordoes not contain only ASCII bytes (i.e. with values in [0; 127]), and unicode()decodes from ASCII by default (on many machines).

失败来自这样一个事实,即author不只包含 ASCII 字节(即值在 [0; 127] 中),并且unicode()默认情况下从 ASCII 解码(在许多机器上)。

A robust solution is to explicitly give the encoding used in your fields; taking UTF-8 as an example:

一个强大的解决方案是明确给出您的字段中使用的编码;以UTF-8为例:

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

(or without the initial u, depending on whether you want a Unicode result or a byte string).

(或没有初始u,取决于您想要 Unicode 结果还是字节字符串)。

At this point, one might want to consider having the authorand publicationfields be Unicode strings, instead of decoding them during formatting.

在这一点上,人们可能需要考虑将authorpublication字段设为 Unicode 字符串,而不是在格式化期间对其进行解码。

回答by Lordn__n

You could also use it clean and simple (but wrong! because you should use formatlike Mark Byers said) by doing:

您也可以通过以下方式使用干净和简单(但错了!因为您应该format像 Mark Byers 所说的那样使用):

print 'This is my %s formatted with %d arguments' % ('string', 2)

回答by Bahadir Tasdemir

You must just put the values into parentheses:

您必须将值放入括号中:

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

Here, for the first %sthe unicode(self.author)will be placed. And for the second %s, the unicode(self.publication)will be used.

在这里,第一个%sunicode(self.author)将被放置。对于第二个%sunicode(self.publication)将使用 。

Note: You should favor string formattingover the %Notation. More info here

注意:你应该有利于string formatting%符号。更多信息在这里

回答by westr

For completeness, in python 3.6 f-string are introduced in PEP-498. These strings make it possible to

为了完整起见,在PEP-498中引入了 python 3.6 f-string 。这些字符串使

embed expressions inside string literals, using a minimal syntax.

使用最少的语法将表达式嵌入字符串文字中。

That would mean that for your example you could also use:

这意味着对于您的示例,您还可以使用:

f'{self.author} in {self.publication}'