我不明白為什么我有一個問題 Traceback(最近一次呼叫最后一次):檔案“main.py”,第 7 行,如果每個 == words[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)
uj5u.com熱心網友回復:
這里有幾個答案,但沒有人提到他為什么會出錯。
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
# you should not increment i here
else:
text_final.append(each)
# instead increment i here
i = 1
print(text_final)
# but by using above code you won't get result you want, you can avoid
index exceeded error
# expected output
['S', 'o', 'm', 'e', 'w', 'a', 'c', 'k', 'y', 'r', 'u', 'n', 'e', 'S', 'a', 't', 'o', 'u', 'r', 'i', 'S', 't', 'f', 'o', 'u', 'n', 'd', 's', 'o', 'm', 'E', 'w', 'a', 'c', 'k', 'y', 'r', 'u', 'n', 'E', 's', 'a', 't', 'o', 'u', 'r', 'i', 's', 't', 'f', 'o', 'u', 'n', 'd', 's', 'o', 'm', 'e', 'w', 'a', 'C', 'k', 'y', 'r', 'u', 'n', 'e', 's', 'a', 't', 'o', 'u', 'r', 'i', 's', 't', 'f', 'o', 'u', 'n', 'd', 's', 'o', 'm', 'e', 'w', 'a', 'c', 'k', 'y', 'R', 'u', 'n', 'e', 's', 'a', 't', 'o', 'u', 'R', 'i', 's', 't', 'f', 'o', 'u', 'n', 'd', 's', 'o', 'm', 'E', 'w', 'a', 'c', 'k', 'y', 'r', 'u', 'n', 'E', 's', 'a', 't', 'o', 'u', 'r', 'i', 's', 't', 'f', 'o', 'u', 'n', 'd', 's', 'o', 'm', 'e', 'w', 'a', 'c', 'k', 'y', 'r', 'u', 'n', 'e', 's', 'a', 'T', 'o', 'u', 'r', 'i', 's', 'T', 'f', 'o', 'u', 'n', 'd']
無需為您的情況使用 while 回圈,您可以使用一個帶有條件的 for 回圈本身來獲得結果。
text_final = ""
for character in text:
if character in words:
text_final = character.upper()
else:
text_final = character.lower()
print(text_final)
# output
SomEwaCkyRunESaTouRiSTfound
uj5u.com熱心網友回復:
您只需要檢查文本中的字符是否存在于單詞中。如果存在,則將該字符的大寫附加到text_final
,否則僅附加相同的字符。
撰寫多種解決方案之一來解決您的問題
>>> text_final = []
>>> text = "somewackyrunesatouristfound"
>>> words = "secret"
>>> i, j = 0, 0
>>> while i < len(words):
... while j<len(text):
... if words[i]==text[j]:
... text_final.append(text[j].upper())
... j =1
... break
... else:
... text_final.append(text[j])
... j =1
... i =1
...
>>> text_final
['S', 'o', 'm', 'E', 'w', 'a', 'C', 'k', 'y', 'R', 'u', 'n', 'E', 's', 'a', 'T']
>>> ''.join(text_final)
'SomEwaCkyRunEsaT'
uj5u.com熱心網友回復:
在您的 while 回圈條件得到滿足之前,您的 i 變數已達到值 6,并且由于您的“單詞”變數中沒有足夠的字母,因此當它到達單詞 [6] 時,它會給出超出范圍的錯誤作為單詞[5] 是變數變數中的最后一個字母。
如果您列印它,這就是您的操作的外觀。
['S'] 1
['S', 'o', 'm', 'E'] 2
['S', 'o', 'm', 'E', 'w', 'a', 'C'] 3
['S', 'o', 'm', 'E', 'w', 'a', 'C', 'k', 'y', 'R'] 4
['S', 'o', 'm', 'E', 'w', 'a', 'C', 'k', 'y', 'R', 'u', 'n', 'E'] 5
['S', 'o', 'm', 'E', 'w', 'a', 'C', 'k', 'y', 'R', 'u', 'n', 'E', 's', 'a', 'T'] 6
不能說你如何解決這個問題,直到你讓問題更清楚地說明你想做什么。
希望這可以幫助。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/491061.html