Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/329.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将列表中的所有项添加到变量?_Python - Fatal编程技术网

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

我是Python的完全初学者,遇到了一个我无法解决的问题。我有一个名为
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)