[英]Python concatenate string & list
I have a list and string:我有一个列表和字符串:
fruits = ['banana', 'apple', 'plum']
mystr = 'i like the following fruits: '
How can I concatenate them so I get (keeping in mind that the enum may change size) 'i like the following fruits: banana, apple, plum'我怎样才能将它们连接起来(请记住,枚举可能会改变大小)“我喜欢以下水果:香蕉、苹果、李子”
Join the list, then add the strings.加入列表,然后添加字符串。
print mystr + ', '.join(fruits)
And don't use the name of a built-in type ( str
) as a variable name.并且不要使用内置类型 (
str
) 的名称作为变量名称。
You can use this code,您可以使用此代码,
fruits = ['banana', 'apple', 'plum', 'pineapple', 'cherry']
mystr = 'i like the following fruits: '
print (mystr + ', '.join(fruits))
The above code will return the output as below:上面的代码将返回如下输出:
i like the following fruits: banana, apple, plum, pineapple, cherry
You can use str.join
.您可以使用
str.join
。
result = "i like the following fruits: "+', '.join(fruits)
(assuming fruits
only contains strings). (假设
fruits
只包含字符串)。 If fruits
contains a non-string, you can convert it easily by creating a generator expression on the fly:如果
fruits
包含非字符串,您可以通过动态创建生成器表达式轻松转换它:
', '.join(str(f) for f in fruits)
You're going to have a problem if you name your variables the same as Python built-ins.如果您将变量命名为与 Python 内置函数相同的名称,则会出现问题。 Otherwise this would work:
否则这会起作用:
s = s + ', '.join([str(fruit) for fruit in fruits])
下面的简单代码将起作用:
print(mystr, fruits)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.