Python 3.x - 使用求和函数连接列表中的字符串
Python 3.x - Using the sum function to concatenate strings in a list
x= ['Good', 'morning'] # example list of strings
我必须使用 sum(x) 来连接两者并打印 (x)。我在将列表转换为整数以使求和函数起作用时遇到问题。
>>>print (sum(x))
'Goodmorning'
这行不通。 sum()
用于累加数字,而不是字符串。请改用 ''.join()
。
>>> ''.join(['good ', 'morning'])
'good morning'
来自帮助(总和)
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.
按照@kevin 的建议,使用join
函数。
x= ['Good', 'morning'] # example list of strings
我必须使用 sum(x) 来连接两者并打印 (x)。我在将列表转换为整数以使求和函数起作用时遇到问题。
>>>print (sum(x))
'Goodmorning'
这行不通。 sum()
用于累加数字,而不是字符串。请改用 ''.join()
。
>>> ''.join(['good ', 'morning'])
'good morning'
来自帮助(总和)
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.
按照@kevin 的建议,使用join
函数。