python - 在输入索引处加入用户输入
问题描述
我似乎无法弄清楚为什么我不能让这个循环循环——它总是会中断。我相信如果它在循环,脚本(希望)会按照指示工作。
我已将说明附加到脚本和内联以解释我的想法。
太棒了!
脚本接受用户输入,每次脚本接收到一个字符串时,它应该将该字符串添加到一个不断增长的字符串中。新添加的字符串应添加到与新添加字符串长度相等的索引处的增长字符串中。如果新添加的字符串的长度等于或大于正在增长的字符串,则此脚本应将新字符串添加到正在增长的字符串的末尾。当此脚本接收到空白输入时,此应用程序应停止接收输入并将不断增长的字符串打印到控制台。
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)
解决方案
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):]
推荐阅读
- android - 如何在 Kotlin 中按类别获取问题
- javascript - k6 负载测试:暂停 ramping-vus 测试执行,然后通过终端命令恢复它
- c# - 泛型类并为集合字段选择基础集合
- python - 如何以“svg 格式”将生成的 QR 码返回到烧瓶 python 中的字节数组?
- mysql - 尝试运行连接器类“io.debezium.connector.mysql.MySqlConnector”时出错
- android - 在 PWA 上将文件上传到 AWS 的问题
- ajax - NextJS - 在页面上保留页眉和页脚
- react-native - React native:ScrollView 中的对齐问题
- csv - Google Apps Script Utilities.parseCsv() 更改小数点和千位分隔符
- c# - ZipFile.CreateFromDirectory UnauthorizedAccessException