簡體   English   中英

如何將列表的值放入字符串

[英]How to put values of a list into a string

我正在嘗試將列表中的多個值放入字符串中。 我的代碼如下:

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

謝謝

您必須打開列表包裝。

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

請參閱文檔: 解壓縮參數列表

>>> 'ID {0}, {1}, and {2}.'.format(*ID)
'ID 0, 1, and 2.'

您需要打開列表包裝。

您的第二個代碼沒有多大意義。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM