0

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?

2 Answers 2

7

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
Sign up to request clarification or add additional context in comments.

4 Comments

Its not an empty string because the user is prompted to enter a word, which is saved as the variable 's'
@HayleyvanWaas, Could you post the full traceback?
@HayleyvanWaas If the string is not empty then s[-1] would not raise IndexError.
@HayleyvanWaas: The IndexError is only raised if s is empty.
5

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.

2 Comments

You could also use a slice here, that'll return an empty string if the string is empty instead of raising an error
@Haidro: I am aware of that; but str.endswith() is self-documenting it's purpose here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.