使用百分号的Python字符串格式

Sai*_*ait 17 python string string-formatting python-3.x

我正在努力做到以下几点:

>>> x = (1,2)
>>> y = 'hello'
>>> '%d,%d,%s' % (x[0], x[1], y)
'1,2,hello'
Run Code Online (Sandbox Code Playgroud)

但是,我有x两个以上的长项,所以我试过:

>>> '%d,%d,%s' % (*x, y)
Run Code Online (Sandbox Code Playgroud)

但这是语法错误.如果不像第一个例子那样编制索引,这样做的正确方法是什么?

fal*_*tru 22

str % .. 接受一个元组作为右手操作数,因此您可以执行以下操作:

>>> x = (1, 2)
>>> y = 'hello'
>>> '%d,%d,%s' % (x + (y,))  # Building a tuple of `(1, 2, 'hello')`
'1,2,hello'
Run Code Online (Sandbox Code Playgroud)

你的尝试应该在Python 3中工作.Additional Unpacking Generalizations支持哪里,但不支持Python 2.x:

>>> '%d,%d,%s' % (*x, y)
'1,2,hello'
Run Code Online (Sandbox Code Playgroud)

  • Actuall扩展的可迭代解包不会**允许语法(python3.4):`>>>'%d,%d,%s'%(*x,y)文件"<stdin>",第1行SyntaxError:只能使用已加星标的表达式作为赋值目标`也许python3.5的[附加拆包推广]允许它(https://www.python.org/dev/peps/pep-0448/) (2认同)

pla*_*mut 10

也许看看str.format().

>>> x = (5,7)
>>> template = 'first: {}, second: {}'
>>> template.format(*x)
'first: 5, second: 7'
Run Code Online (Sandbox Code Playgroud)

更新:

为了完整起见,我还包括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'
Run Code Online (Sandbox Code Playgroud)

但是,在Python 3.4及更低版本中,如果要在解压缩后的元组之后传递其他参数,最好将它们作为命名参数传递:

>>> x = (5, 7)
>>> y = 42
>>> template = 'first: {}, second: {}, last: {last}'
>>> template.format(*x, last=y)
'first: 5, second: 7, last: 42'
Run Code Online (Sandbox Code Playgroud)

这避免了在最后构建包含一个额外元素的新元组的需要.

  • 如何在我之前的例子中采用这个?`'{},{},{}'.format(*x,y)`仍然不起作用? (2认同)