【问题标题】:How to put values of a list into a string如何将列表的值放入字符串
【发布时间】:2010-01-08 12:03:35
【问题描述】:

我正在尝试将列表中的多个值放入字符串中。我的代码如下:

ID = [0, 1, 2]
print 'ID {0}, {1}, and {2}.'.format(ID)

print (r'(ID\s*=\s*)(\S+)').format(ID)

这不起作用。有谁知道我要去哪里错了。 第二行代码打印出列表:

[0, 1, 2]

第一行说:

File "tset.py", line 39, in b
    print 'ID {0}, {1}, and {2}.'.format(ID)
IndexError: tuple index out of range

谢谢

【问题讨论】:

  • 代码不起作用不是解释。你有什么错误吗?
  • 哦,亲爱的。看,您的第二次添加与最初提出的问题几乎没有关系。请删除它并提出一个新问题。而且您需要包含格式正确的完整代码,而不是一些随机片段。

标签: python string-formatting


【解决方案1】:

你必须解压清单。

ID = [0, 1, 2]
print 'ID {0}, {1}, and {2}.'.format(*ID)

请参阅文档:Unpacking argument lists

【讨论】:

    【解决方案2】:
    >>> 'ID {0}, {1}, and {2}.'.format(*ID)
    'ID 0, 1, and 2.'
    

    你需要解开你的清单。

    您的第二个代码没有多大意义。

    【讨论】:

      猜你喜欢
      • 2020-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-29
      相关资源
      最近更新 更多