带百分号的 Python 字符串格式

标签 python string python-3.x string-formatting

我正在尝试执行以下操作:

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

相关文章:

python - 为什么鼠标悬停数据消失

python - 利用洪水填充算法确定等高 map 区域

python - DataFrame 列的所有可能组合 - pandas/python

c# - 删除两个字符串之间的字符串的一部分

python - 更改字典中特定键的特定值

python - 将 Python Flask App 部署到 Heroku R10 报错

python - 神秘的 "embedded null byte"错误

string - python : remove single quotation in a string in a list

javascript - jQuery 文本 html 操作,在大量文本中查找字符的出现,然后更改其颜色

python - 在 BeautifulSoup 中用另一种标签替换一种标签