你如何连接一个列表?
How do you concatenate with a list?
我对 python 比较陌生,我正在尝试连接列表。这是我最好的尝试,但显然它不起作用。有人知道这样做的方法吗?谢谢
present = ["Jake", "Jimmy", "Karen"]
print("The people present are " + present)
您需要先将列表转换为字符串,然后才能使用 +
运算符进行字符串连接。您可以使用 str.join()
方法来完成此操作。
present = ["Jake", "Jimmy", "Karen"]
print("The people present are " + ", ".join(present))
这将为列表中的每个项目创建一个字符串,并使用字符串 ', '
作为每个元素之间的分隔符。
在此处查看 w3 学校示例 https://www.w3schools.com/python/ref_string_join.asp
或官方python文档https://docs.python.org/3/library/stdtypes.html#str.join
你可能想要str.join
>>> some_list = ['Jack', 'Jill', 'Hill']
>>> print("The story centrally features the characters: " + ", ".join(some_list))
The story centrally features the characters: Jack, Jill, Hill
我对 python 比较陌生,我正在尝试连接列表。这是我最好的尝试,但显然它不起作用。有人知道这样做的方法吗?谢谢
present = ["Jake", "Jimmy", "Karen"]
print("The people present are " + present)
您需要先将列表转换为字符串,然后才能使用 +
运算符进行字符串连接。您可以使用 str.join()
方法来完成此操作。
present = ["Jake", "Jimmy", "Karen"]
print("The people present are " + ", ".join(present))
这将为列表中的每个项目创建一个字符串,并使用字符串 ', '
作为每个元素之间的分隔符。
在此处查看 w3 学校示例 https://www.w3schools.com/python/ref_string_join.asp
或官方python文档https://docs.python.org/3/library/stdtypes.html#str.join
你可能想要str.join
>>> some_list = ['Jack', 'Jill', 'Hill']
>>> print("The story centrally features the characters: " + ", ".join(some_list))
The story centrally features the characters: Jack, Jill, Hill