首页 > 解决方案 > 在输入索引处加入用户输入

问题描述

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

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

太棒了!

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

    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)

标签: pythonpython-3.xwhile-loop

解决方案


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):]


推荐阅读