python - 如何从列表中的多个字符串中打印出 1 个字符串

标签 python string list

我在为 Join all exercise 中的“Hands-on Python Tutorial of Andrew N. Harrington”找到解决方案时遇到了一些麻烦。 .

基本上,练习是采用仅由字符串组成的 ['very', 'hot', 'day'] 列表,并从中生成一个字符串,在本例中'veryhotday'.

This is the exercise :

'''exercise to complete and test this function'''
def joinStrings(stringList):
    '''Join all the strings in stringList into one string,
    and return the result, NOT printing it. For example:
    >>> s = joinStrings(['very', 'hot', 'day'])
    >>> print(s)  # I can print s OUTSIDE joinStrings
    'veryhotday'
    '''
    # finish the code for this function

def main():
    print(joinStrings(['very', 'hot', 'day']))
    print(joinStrings(['this', 'is', 'it']))
    print(joinStrings(['1', '2', '3', '4', '5']))

main()

所以只有第一个定义可以改变。我是这样解决的:

def joinStrings(stringList):
    return ''.join(stringList)

我相信这是可行的并且是正确的。如果我在这里错了,请纠正我,但问题是它必须以不同的方式解决。我必须积累不同的字符串。就像他们在这里用整数显示的那样:

def sumList(nums):
    ’’’Return the sum of the numbers in the list nums.’’’
    sum = 0
    for num in nums:
        sum = sum + num
    return sum

我真的想不通,所以请帮助我!

最佳答案

''.join(stringList) 是正确的方法。有什么问题?

如果必须以不同的方式完成,您可以执行以下操作之一:

import operator
return reduce(operator.add, stringList)

甚至

s = ''
for string in stringList:
    s = s + string
return s

但这是不必要的复杂化,因为像您建议的那样使用 join 是最简单和首选的方法。可能也是最快的。

关于python - 如何从列表中的多个字符串中打印出 1 个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12392723/

相关文章:

python - 为什么字符串乘法的字节码不同?

python - 处理溢出错误: math range error in Python with NumPy

python - 以惯用的方式在 Python 中遍历 os.walk 中的各个文件

java - 我怎样才能将一个项目 'replicate' 放入一个包含 n 个引用的列表中?

python - 如何根据其他列的某些值替换列的 nan 值

python - 将年份和日期转换为 Pandas 中的日期时间索引

MySQL 字符串转为日期/时间或时间戳

python - 如果出现子字符串,则拆分字符串

Python - 比较来自txt文件的字符串输入

r - 将数据帧列表转换为 R 中的单个数据帧