索引超出范围,同时循环进入循环python
我不明白为什么我有一个问题的追溯(最近的电话): 文件“ main.py”,第7行,in 如果每个==单词[i]: indexError:字符串索引超出范围。
感谢您的帮助。
text_final = []
text = "somewackyrunesatouristfound"
words = "secret"
i = 0
while i < len(words):
for each in text:
if each == words[i]:
text_final.append(each.upper())
i+=1
else:
text_final.append(each)
print(text_final)
I don't understand why i have an issue Traceback (most recent call last):
File "main.py", line 7, in
if each == words[i]:
IndexError: string index out of range.
Thanks for your help.
text_final = []
text = "somewackyrunesatouristfound"
words = "secret"
i = 0
while i < len(words):
for each in text:
if each == words[i]:
text_final.append(each.upper())
i+=1
else:
text_final.append(each)
print(text_final)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这里有几个答案,但没有人提到他为什么遇到错误。
循环时不需要使用,您可以得到结果
使用一个条件进行循环。
Couple of answers here but no body mentions why he got the error.
no need to use while loop for your case, you can get result
using one for loop itself with condition.
您只需要检查文本中的字符是否以文字存在。如果存在,则将该字符的上限附加到
text_final
,否则仅附加相同的字符。写出解决问题的众多解决方案之一
you just need to check if character in text is present in words or not. if it is present then append upper case of that character to
text_final
, otherwise append that same character only.writing one of many solution way to solve your problem
您的I变量在满足您的wir循环条件之前已达到值6,并且由于您的“单词”变量没有足够[5]是您的最后一个字母,用单词变量。
如果您打印它,这就是您的OP的外观。
无法说出如何解决这个问题,直到您对要做什么更清楚地提出问题为止。
希望这会有所帮助。
Your i variables is reaching the value 6 before your while loop condition is getting satisfied, and since your "words" variables does not have enough letters within it, when it reaches words[6], it will give a out of range error as words[5] is your last letter in the words variables.
This is how your op will look if you print it.
Cant say on how you can solve this, until you make the question clearer on what you want to do.
Hope this helps.