簡體   English   中英

如何修復 python 中的“字符串索引超出范圍”錯誤?

[英]How to fix'string index out of range' error in python?

我試圖制作一個程序,用某些數字替換字母或字母組,但程序返回'IndexError:字符串索引超出范圍'。 這是什么原因造成的?

phr = input('Frase: ')
phr=phr.lower()
out = ''
for pos in range(len(phr)):
    frpos=pos+1
    if phr[pos]=='h'and phr[frpos]=='e':
        out+='1'
    if phr[pos]=='h':
        out+='2'
print(out)

您在開始時增加 FRPOS,因此最后一個字符沒有值。

試試這個,它應該工作:

phr = input('Frase: ')
phr=phr.lower()
out = ''
for pos in range(len(phr)):
    frpos=pos
    if phr[pos]=='h'and phr[frpos]=='e':
        out+='1'
    if phr[pos]=='h':
        out+='2'
    pos + 1
print(out)

考慮aaaah的情況。

找到“h”后,您的代碼還將檢查“h”后的 position 是否有“e”。 這種情況是導致您的程序中斷的原因。 為了解決這個問題,一個簡單的解決方法是檢查“frpos”是否有效,如下所示:

phr = input('Frase: ')
phr=phr.lower()
out = ''
for pos in range(len(phr)):
    frpos=pos+1
    if phr[pos]=='h'and frpos<len(phr) and phr[frpos]=='e':
        out+='1'
    if phr[pos]=='h':
        out+='2'
print(out)

干杯

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM