【问题标题】:join user input at index of inputs在输入索引处加入用户输入
【发布时间】:2020-11-30 15:08:09
【问题描述】:

我似乎无法弄清楚为什么我不能让这个循环循环 - 它总是会中断。我相信如果它是循环的,脚本(希望)会按照指示工作。

我已将说明附加到脚本和内联以解释我的想法。

谢谢!

脚本接受用户输入,每次脚本接收到一个字符串时,它应该将该字符串添加到一个不断增长的字符串中。新添加的字符串应添加到与新添加字符串长度相等的索引处的增长字符串中。如果新添加的字符串的长度等于或大于正在增长的字符串,则此脚本应将新字符串添加到正在增长的字符串的末尾。当此脚本接收到空白输入时,此应用程序应停止接收输入并将不断增长的字符串打印到控制台。

    if __name__ == "__main__":
user_word = input()
second_word = input()
results = user_word + second_word[:]
i = results
while results == "":  # When script receives a blank input
    print(results)  # stop receiving input and print the growing string
    break

if user_word >= results:  # if newly added string length equal to or larger
    results = user_word + second_word[:]
    user_word.join(results)  # the new string added to end of the growing string.
    print(results)

if user_word < results:  # new string is shorter than the existing string THEN
    results = user_word + second_word[:]  # add the new string at the index equal to the new string length.
    user_word.join(results)  # Newly added strings should be added to the growing string
    print(results)

【问题讨论】:

  • 它甚至没有正确缩进它是如何工作的?
  • 你明白我的回答吗?
  • 我认为由于某种原因,我粘贴时缩进搞砸了。它实际上是事先格式化的。

标签: python python-3.x while-loop


【解决方案1】:
s = ''

while True:
  user_word = input('Enter string')
  if len(user_word) >= len(s):
    s = s + user_word
  elif user_word == '':
    print(s)
    break
  else:
    s = s[:len(user_word)] + user_word + s[len(user_word):]

【讨论】:

  • 请为您的答案添加一些解释。解释底层逻辑比仅仅给出代码更重要。它可以帮助作者和其他读者自己解决这个问题和类似问题,同时为他们提供扩展编程技能所需知识的线索。
  • 操作者清楚地理解它,或者会说些什么@Ironkey
  • 这个假设根本不正确,他们可能正在试图弄清楚它是如何在这一刻起作用的
  • 用户在 57 分钟前被看到,我在 2 小时前回答。由于这是一个专家主题,我假设操作已被理解。但是我会问操作人员是否需要解释@Ironkey
  • 我们去他们接受了。 但是为了将来的参考,您不仅要回答 OP,还要回答所有来到该网站寻找此问题答案的其他人。所以无论如何最好添加解释。恭喜你的代码被接受并快乐:^)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-11-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多