繁体   English   中英

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

[英]How do I concatenate strings in a while loop?

因此,我试图做到这一点,以便我可以输入多个字符串,它将所有字符串连接在一起。 但是每次它只返回一个字符串,而不添加它们。

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

代码的问题是,您没有设置适当的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()

我已经在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) 

希望它能工作!

在代码中,您始终返回s,即用户输入的字符串。 该返回将导致该函数说:“嘿,我完成了。 你现在可以继续。” return语句之后的所有语句都不会被调用,您的程序将直接跳出循环。

因此,请删除循环中的所有返回值,因为您不想在用户仍在输入字符串时结束该函数。 您应该考虑使用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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM