简体   繁体   中英

How to fix a String index out of range exception in Python

There is some issue with my python code. I am making a program that finds the occurrences of the letter A in a word and if that letter is found and the next letter is not the letter A the A is swapped with the next letter.

As an example TAN being TNA but WHOA staying as WHOA AARDVARK being ARADVRAK

The issue is when I input ABRACADABRA I get a string index out of range exception. Before I had that exception I had the word that prints it as BRACADABR Ii'm not sure why if I have to add another loop in my program.

If you guys also have anymore efficient way to run the code then the way I have please let me know!

def scrambleWord(userInput):
    count = 0
    scramble = ''
    while count < len(userInput):
        if userInput[count] =='A' and userInput[count+1] != 'A':
            scramble+= userInput[count+1] + userInput[count] 
            count+=2
        elif userInput[count] != 'A':
            scramble += userInput[count]
            count+=1
    if count < len(userInput):
       scramble += userInput(len(userInput)-1)
    return scramble


        #if a is found switch the next letter index with a's index
def main():
    userInput = input("Enter a word: ")
    finish = scrambleWord(userInput.upper())
    print(finish)
main()

When you get to the end of the string and it is an 'A' your program is then asking for the next character which is off the end of the string.

Change the loop so it doesn't include the last character:

while count < len(userInput)-1:
    if ...

You can modify your code as below:

def scrambleWord(userInput):
    count = 0
    scramble = ''
    while count < len(userInput):
        if count < len(userInput)-1 and userInput[count] =='A' and userInput[count+1] != 'A':
            scramble+= userInput[count+1] + userInput[count] 
            count+=2
        else:
            scramble += userInput[count]
            count+=1
    return scramble

You are not checking the condition ( count < len(userInput)-1 ) when logic tries to check for A 's occurrence and swap with next letter. It throws string index out of range exception.

The issue arises in your code when last character in input is 'A'. This is because your first if in the loop tries to access 'count + 1' character during last iteration. And since there's no character at that position, you get index error.

The simplest solution would be to make a separate if condition for the same. Updated snippet for while loop might look like this -

# while start
while count < len_: # len_ is length of input
    if count + 1 >= len_:
        break # break outta loop, copy last character

    current = inp[count]
    next_ = inp[count + 1]

    if current == 'A':
        op += ( next_ + current) # op is result
        count += 1
    else:
        op += current

     # increment counter by 1
     count += 1

# rest of the code after while is same

Another small issue in your code is while copying last character ( after loop ends ), you should use [ ] instead of ( ) to refer last character in input string.

Just for fun :

from functools import reduce
def main():
    word = input("Enter a word: ").lower()
    scramble = reduce((lambda x,y : x[:-1]+y+'A' \
        if (x[-1]=='a' and y!=x[-1]) \
        else x+y),word)
    print(scramble.upper())
main()

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