python - 在python中循环替换单词
问题描述
这段代码有什么问题:我试图在循环中运行这段代码,每个循环都需要两个参数,但它不起作用,它只运行两次然后不断打印不必要的东西。
代码:
words= "this is my computer and my computer is super computer"
wordlist = words.split(" ")
changed_wordlist=[]
while (True):
replace = input("replace this: ")
with_this = input("with this: ")
for word in wordlist:
if word == replace:
replacedword = word.replace(replace, with_this)
print(replacedword,end=" ")
changed_wordlist.append(replacedword)
elif word!= replace:
print(word,end=" ")
changed_wordlist.append(word)
wordlist = changed_wordlist
解决方案
我创建了一个示例,该示例将更改列表中的单词,然后在更改后打印其内容,无论是否找到该单词。尝试这个:
words = "this is my computer and my computer is super computer"
wordlist = words.split(" ")
while (True):
replace = input("replace this: ")
with_this = input("with this: ")
# Iterate over the list, looking for the word
# to replace
for i in range(len(wordlist)):
# If we find the word, we replace it
if wordlist[i] == replace:
wordlist[i] = with_this
print("The list is now: " + str(wordlist))
推荐阅读
- amazon-web-services - Api Gateway websocket $connect 从 http 集成点获得 400 但它适用于其他路由
- reactjs - 将 Material-ui 网格添加到 React 页面时,Jenkins 构建失败
- html - HTML 元素在打开后移动
- r - 从网络源渲染图像
- javascript - 如何在 _app.js 中使用 getStaticProps 在 Next.js 的每个页面中显示从 api 获取的数据
- c# - 如何修复呈现一致微小差异的 int 到 hex 转换?
- html - CSS渐变动画出现静止
- ios - xCode 既不接受开发证书也不接受分发
- python - 如何提取文档中具有特定结构的 MONGODB 集合的前 N 个元素
- python - 如何限制python进程的CPU周期和内存