flarezel
flarezel

Reputation: 81

Why do I get "IndexError: string index out of range"?

I'm currently a beginner to python and coding in general.

I am doing this quiz online which tasks you to remove signs (*_`~) from the front and end of a string. Eg.(~~hidden ~ tilde~~ will be changed to hidden ~ tilde) keeping the sign in the middle.

This is my code:

string = input()
signs = " *_`~ "
for sign in string:
    if sign in signs:
        if sign == string[0]:
            string = string.lstrip(sign)
            string = string.rstrip(sign)
print(string)

Which gets this error: IndexError: string index out of range

I'm just a noob trying to get started on python..plz help :(

Upvotes: 2

Views: 65

Answers (1)

baao
baao

Reputation: 73241

The entire code is unneccessary. Just use strip

signs = " *_`~ "
string = "*fo * o*"
print(string.strip(signs)) # fo * o

Upvotes: 5

Related Questions