gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 22:45:45 27 4
gpt4 key购买 nike

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

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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com