简体   繁体   English

Python 3.x-使用sum函数连接列表中的字符串

[英]Python 3.x - Using the sum function to concatenate strings in a list

x= ['Good', 'morning'] # example list of strings

I have to use sum(x) to concatenate both and print (x). 我必须使用sum(x)来连接两者和打印(x)。 I'm having trouble converting the list into integers for the sum function to work. 我在将列表转换为整数以使sum函数正常工作时遇到麻烦。

>>>print (sum(x))
'Goodmorning'

This doesn't work. 这行不通。 sum() is for adding up numbers, not strings. sum()用于相加数字,而不是字符串。 Use ''.join() instead. 使用''.join()代替。

>>> ''.join(['good ', 'morning'])
'good morning'

From help(sum) 来自帮助(求和)

Help on built-in function sum in module builtins:

sum(...)
    sum(iterable[, start]) -> value

    Return the sum of an iterable of numbers (NOT strings) plus the value
    of parameter 'start' (which defaults to 0).  When the iterable is
    empty, return start.

As @kevin suggested, use join function. 如@kevin所建议,请使用join函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM