带有百分号的 Python 字符串格式 [英] Python string formatting with percent sign
本文介绍了带有百分号的 Python 字符串格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在努力做到以下几点:
<预><代码>>>>x = (1,2)>>>y = '你好'>>>'%d,%d,%s' % (x[0], x[1], y)'1,2,你好'然而,我有一个很长的x
,不止两个项目,所以我尝试了:
但这是语法错误.没有像第一个示例那样建立索引的正确方法是什么?
解决方案
str % ..
接受元组作为右手操作数,因此您可以执行以下操作:
您的尝试应该适用于 Python 3.其中 附加解包概括
受支持,但在 Python 2.x 中不支持:
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?
解决方案
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'
这篇关于带有百分号的 Python 字符串格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文