Python 如何将列表中的所有项添加到变量?
我是Python的完全初学者,遇到了一个我无法解决的问题。我有一个名为Python 如何将列表中的所有项添加到变量?,python,Python,我是Python的完全初学者,遇到了一个我无法解决的问题。我有一个名为body的变量,我将它传递到一个函数中,以便在电子邮件中发送。然后我有一个名为items的列表,我想把它放在邮件正文中 我的代码如下所示: body = "The following items are in the list:" 如何将items列表中的所有项追加到body变量中字符串的末尾?类似的操作应该是: body = str("The following items are in the list: ") item
body
的变量,我将它传递到一个函数中,以便在电子邮件中发送。然后我有一个名为items
的列表,我想把它放在邮件正文中
我的代码如下所示:
body = "The following items are in the list:"
如何将
items
列表中的所有项追加到body
变量中字符串的末尾?类似的操作应该是:
body = str("The following items are in the list: ")
items = ["a", "b", "c", "d"] # list of strings
for i in items:
body = body.__add__(i + ",")
print(body)
输出:
The following items are in the list: first second
some\u string.join(list)
返回在所有元素之间添加了some\u string
的字符串。您可以使用python的字符串格式来完成以下操作:
body = "The following items are in the list:"
items = ["first", "second", "third"]
body = "{} {}.".format(body, ' '.join(items))
会回来的
'The following items are in the list: first second third.'
谢谢,效果很好。我还没学会魔法!这甚至不是有效的python代码(python使用
作为注释,而不是/
),为什么要使用\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu。
'The following items are in the list: first second third.'
# choose a delimiter for items in the list
delimiter = ' '
# join each item in the list separated by the delimiter
items_str = delimiter.join(str(i) for i in items)
body = "The following items are in the list: {}".format(item_str)