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

时间:2015-01-29 06:01:49

标签: 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)

4 个答案:

答案 0 :(得分:3)

以下是我假设你要做的事情:

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: "), ''))

答案 1 :(得分:1)

您的代码问题是,您没有输入正确的break条件,而是在阅读第一个输入项后刚刚返回。

def addWords():
    resultant = ''
    delimiter = ' '
    while True:
        user_input = raw_input('I will echo your input until you enter return only:') # use raw_input() for python2
        if not user_input:
            break
        resultant += delimiter + user_input
    return resultant
addWords()

答案 2 :(得分:0)

我已经在python 2.7中实现了它

def addwords():
      s = 'a'
      a = ''
      while s != '':
              s = raw_input( ' I will echo your input until you enter return only: ') # python 2.7 syntax
              a = a + s
      return (a) 

希望它能起作用!!

答案 3 :(得分:0)

在您的代码中,您始终返回s,即用户输入的字符串。而那次回归将导致这个功能如此说:'嘿,我已经完成了。你现在可以继续。“返回语句之后的所有语句都不会被调用,程序将直接跳出循环。

因此,删除循环中的所有返回,因为您不想在用户仍在输入字符串时结束该功能。你应该考虑使用raw_input(),因为正常的input()将允许输入整数,如下所示:

while ...:
    s = raw_input("...")
    a += s

您应该注意到,声明a + = s与a = a + s相同。

接下来,当他输入他的字符串时,循环中的输入消息可能会分散用户的注意力。您可以向他打印一条消息,然后在循环中请求输入而不显示消息。但是,显然,这对您的代码来说并不是必需的。这是一个例子:

print "Hey, you can enter strings as long as you dont hit enter directly."
while ...:
     s = raw_input()
     # go on

最后,优化的一件事是你结束循环的条件。就像现在一样,它将再次添加字符串。 要解决此问题,您可以在while循环中添加一个条件,以检查用户是否输入了空字符串:

if s == '':
    break

然后您可以将循环更改为:

while True:
     # ...

现在你只需要在while循环之后返回整个字符串。

while True:
    # ...
return a

一段代码中的所有这些更改都将如下所示:

def addWords():
    print "Hey, you can enter strings as long as you dont hit enter directly."
    a = ''
    while True:
        s = raw_input()
        if s == '':
            break
        a += s
    return a

我在手机上回答这个问题,所以请原谅我的错误。

我希望我能帮助你。 1Darco1

相关问题