简体   繁体   中英

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

Im trying to make a program that replaces letters or groups of letters with certain numbers, but the program returns 'IndexError: string index out of range'. What is causing this?

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)

You are incrementing the FRPOS in the beginning and hence in the end there is no value for the last character.

Try this, it should work:

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)

Consider the case aaaah .

Upon finding 'h' your code will also check the position after the 'h' for an 'e'. This sort of situations is what causes your program to break. In order to solve the issue, an easy fix would be to check whether 'frpos' is valid as follows:

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)

Cheers

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM