Python连接字符串&lis

2024-04-28 10:56:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个列表和字符串:

fruits = ['banana', 'apple', 'plum']
mystr = 'i like the following fruits: '

如何连接它们以便获得(请记住枚举可能会更改大小) “我喜欢以下水果:香蕉、苹果、李子”


Tags: the字符串苹果apple列表likebananafollowing
3条回答

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

print mystr + ', '.join(fruits)

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

你可以用这个代码

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

上述代码将返回如下输出:

i like the following fruits: banana, apple, plum, pineapple, cherry

您可以使用^{}

result = "i like the following fruits: "+', '.join(fruits)

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

', '.join(str(f) for f in fruits)

相关问题 更多 >