python - 如何在 while 循环中连接字符串?

标签 python string concatenation

所以我正在努力做到这一点,这样我就可以输入多个字符串,它会连接所有的字符串。但每次它只返回一个字符串而不添加它们。

def addWords():
    s = 'a'
    while s != '':
        s = input( ' I will echo your input until you enter return only: ')
        return(s)
        a = a + s
        return (a)

最佳答案

这是我假设您正在尝试做的事情:

def add_words():
    a = ''
    s = 'a'
    while s != '':
        s = input("I will echo your input until you enter return only: ")
        a += s # equivalent to a = a + s
    # we exit the code block when they enter the empty string
    return a

但实际上你应该这样做:

def add_words():
    accumulator = ''
    while True:  # loop forever
        s = input("I will echo your input until you enter return only: ")
        if not s:  # if s is the empty string...
            break  # leave the infinite loop
        accumulator += s
    return accumulator

当您学习 itertools 魔法时,您可以制作一些东西(公认的丑陋),例如...

def add_words():
    return "".join(iter(lambda: input("I will echo your input until you enter return only: "), ''))

关于python - 如何在 while 循环中连接字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28207925/

相关文章:

python - 将 Python 输入字符串限制为特定字符和长度

python - 在 Python 中重现 MATLAB 的 imgaborfilt

c# - 从最高到最低的 C# 重新排列一串数字

c - 在C中读取数据文件中的条目数

c++ - Arduino - 将 int 值附加到字符串的末尾以连接变量

java - String n = new String( char + int) 添加但应该连接

python - 在 Alpine Linux 上安装 pycurl 时出现 “Could not run curl-config: [Errno 2] No such file or directory”

python - 指导 Pip 使用 Python 3

c - C中的字符串回文

mysql - Concat 在 MySQL 中不起作用