我正在尝试执行以下操作:
>>> x = (1,2)
>>> y = 'hello'
>>> '%d,%d,%s' % (x[0], x[1], y)
'1,2,hello'
但是,我的x
很长,不止两个,所以我试了一下:
>>> '%d,%d,%s' % (*x, y)
但这是语法错误。没有像第一个示例那样索引的正确方法是什么?
最佳答案
str % ..
接受 tuple 作为右手操作数,因此您可以执行以下操作:
>>> x = (1, 2)
>>> y = 'hello'
>>> '%d,%d,%s' % (x + (y,)) # Building a tuple of `(1, 2, 'hello')`
'1,2,hello'
您的尝试应该在 Python 3 中工作,其中 Additional Unpacking Generalizations
支持,但在 Python 2.x 中不支持:
>>> '%d,%d,%s' % (*x, y)
'1,2,hello'
关于带百分号的 Python 字符串格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31964930/