Hayley van Waas
Hayley van Waas

Reputation: 439

Why is this giving me an index error in python?

In the code below, s refers to a string (although I have tried converting it to a list and I still have the same problem).

s = "".join(s)
if s[-1] == "a":
    s += "gram"

I the last item in the string is the letter "a", then the program needs to add the string "gram" to the end of the string 's' represents.

e.g. input:

s = "insta"

output:

instagram

But I keep getting an IndexError, any ideas why?

Upvotes: 0

Views: 69

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1122242

If s is empty, there is no last letter to test:

>>> ''[-1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: string index out of range

Use str.endswith() instead:

if s.endswith('a'):
    s += 'gram'

str.endswith() does not raise an exception when the string is empty:

>>> 'insta'.endswith('a')
True
>>> ''.endswith('a')
False

Alternatively, using a slice would also work:

if s[-1:] == 'a':

as slices always return a result (at minimum an empty string) but str.endswith() is more self-evident as to what it does to the casual reader of your code.

Upvotes: 5

falsetru
falsetru

Reputation: 369134

If s is empty string s[-1] causes IndexError:

>>> s = ""
>>> s[-1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: string index out of range

Instead of s[-1] == "a", you can use s.endswith("a"):

>>> s = ""
>>> s.endswith('a')
False
>>> s = "insta"
>>> s.endswith('a')
True

Upvotes: 7

Related Questions