带有百分号的 Python 字符串格式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31964930/
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
Python string formatting with percent sign
提问by Sait
I am trying to do exactly the following:
我正在尝试执行以下操作:
>>> x = (1,2)
>>> y = 'hello'
>>> '%d,%d,%s' % (x[0], x[1], y)
'1,2,hello'
However, I have a long x
, more than two items, so I tried:
但是,我有一个很长的x
,超过两个的项目,所以我尝试了:
>>> '%d,%d,%s' % (*x, y)
but it is syntax error. What would be the proper way of doing this without indexing like the first example?
但它是语法错误。没有像第一个例子那样索引的正确方法是什么?
采纳答案by falsetru
str % ..
accepts a tuple as a right-hand operand, so you can do the following:
str % ..
接受元组作为右手操作数,因此您可以执行以下操作:
>>> x = (1, 2)
>>> y = 'hello'
>>> '%d,%d,%s' % (x + (y,)) # Building a tuple of `(1, 2, 'hello')`
'1,2,hello'
Your try should work in Python 3. where Additional Unpacking Generalizations
is supported, but not in Python 2.x:
您的尝试应该在 Python 3 中工作。Additional Unpacking Generalizations
支持的地方,但在 Python 2.x 中不支持:
>>> '%d,%d,%s' % (*x, y)
'1,2,hello'
回答by plamut
Perhaps have a look at str.format().
也许看看str.format()。
>>> x = (5,7)
>>> template = 'first: {}, second: {}'
>>> template.format(*x)
'first: 5, second: 7'
Update:
更新:
For completeness I am also including additional unpacking generalizationsdescribed by PEP 448. The extended syntax was introduced in Python 3.5, and the following is no longer a syntax error:
为了完整起见,我还包括了PEP 448描述的其他解包概括。Python 3.5中引入了扩展语法,以下不再是语法错误:
>>> x = (5, 7)
>>> y = 42
>>> template = 'first: {}, second: {}, last: {}'
>>> template.format(*x, y) # valid in Python3.5+
'first: 5, second: 7, last: 42'
In Python 3.4 and below, however, if you want to pass additional arguments after the unpacked tuple, you are probably best off to pass them as named arguments:
但是,在Python 3.4 及以下版本中,如果您想在解包的元组之后传递额外的参数,您可能最好将它们作为命名参数传递:
>>> x = (5, 7)
>>> y = 42
>>> template = 'first: {}, second: {}, last: {last}'
>>> template.format(*x, last=y)
'first: 5, second: 7, last: 42'
This avoids the need to build a new tuple containing one extra element at the end.
这避免了在末尾构建一个包含一个额外元素的新元组的需要。
回答by Fabio Menegazzo
I would suggest you to use str.format
instead str %
since its is "more modern" and also has a better set of features. That said what you want is:
我建议您str.format
改用str %
它,因为它“更现代”并且还具有更好的功能集。那就是说你想要的是:
>>> x = (1,2)
>>> y = 'hello'
>>> '{},{},{}'.format(*(x + (y,)))
1,2,hello
For all cool features of format
(and some related to %
as well) take a look at PyFormat.
对于所有很酷的功能format
(以及一些与之相关的功能%
),请查看PyFormat。