Python连接字符串和列表

use*_*110 18 python

我有一个列表和字符串:

fruits = ['banana', 'apple', 'plum']
mystr = 'i like the following fruits: '
Run Code Online (Sandbox Code Playgroud)

我如何连接它们以便得到(记住枚举可能会改变大小)'我喜欢以下水果:香蕉,苹果,李子'

Ign*_*ams 21

加入列表,然后添加字符串.

print mystr + ', '.join(fruits)
Run Code Online (Sandbox Code Playgroud)

并且不要使用内置类型(str)的名称作为变量名.


mgi*_*son 5

您可以使用str.join

result = "i like the following fruits: "+', '.join(fruits)
Run Code Online (Sandbox Code Playgroud)

(假设fruits仅包含字符串)。如果fruits包含非字符串,您可以通过动态创建生成器表达式来轻松转换它:

', '.join(str(f) for f in fruits)
Run Code Online (Sandbox Code Playgroud)


mbg*_*irp 5

您可以使用此代码,

fruits = ['banana', 'apple', 'plum', 'pineapple', 'cherry']
mystr = 'i like the following fruits: '
print (mystr + ', '.join(fruits))
Run Code Online (Sandbox Code Playgroud)

上面的代码将返回如下输出:

i like the following fruits: banana, apple, plum, pineapple, cherry
Run Code Online (Sandbox Code Playgroud)