Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IndexError: string index out of range - with len()

Tags:

python

string

I'm currently trying to make a simple code (basically mad-libs) and I made a variable called time. The user is supposed to type in something like months or days. If a user inputs month or day, an if statement is supposed to add an "s" to make it plural:

time = str(input("Pick a measurement of time (ex. days): "))
if time[len(time)] != "s":
   time = time + "s"

When I test this code out, it gives me this error:

Traceback (most recent call last):
   File "D:/nikis_staff/PROGRAMMING/madlibs.py", line 51, in <module>
      if time[len(time)] != "s":
IndexError: string index out of range

I know that string index out of range means the string is longer than I thought it was but I am using len().

like image 370
nikodem363 Avatar asked Nov 16 '25 08:11

nikodem363


2 Answers

Indexes in Python begin with 0, i.e. the first element in a string, list, tuple, etc. is: 0. Hence the last element of s is len(s)-1. So time[len(time)] addresses the element after the last element, which of course causes an IndexError. Use time[len(time) - 1] instead, or better yet: time[-1].

Often you will find slicing s[-1:] helpful, too, because it returns '' for an empty string instead of raising an IndexError.

C.f. http://www.tutorialspoint.com/python/python_lists.htm

like image 89
kay Avatar answered Nov 19 '25 00:11

kay


If a string is of length 5, like 'hello', then the max index is 4 since indexing is zero-based (starts from 0, not 1).

>>> len('hello')
5
>>> 'hello'[4]
'o'

You can avoid calculating the length by using relative offsets for the index. So, if you want the last character, use -1, like this:

>>> 'hello'[-1]
'o'
like image 38
Burhan Khalid Avatar answered Nov 18 '25 22:11

Burhan Khalid



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!