Python string formatting with percent sign

别来无恙 提交于 2019-12-10 12:40:24

问题


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:

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


回答1:


str % .. accepts a tuple as a right-hand operand, so you can do the following:

>>> 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:

>>> '%d,%d,%s' % (*x, y)
'1,2,hello'



回答2:


Perhaps have a look at str.format().

>>> x = (5,7)
>>> template = 'first: {}, second: {}'
>>> template.format(*x)
'first: 5, second: 7'

Update:

For completeness I am also including additional unpacking generalizations described by PEP 448. The extended syntax was introduced in Python 3.5, and the following is no longer a syntax error:

>>> 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:

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




回答3:


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:

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



来源:https://stackoverflow.com/questions/31964930/python-string-formatting-with-percent-sign

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!