nikodem363
nikodem363

Reputation: 33

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

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().

Upvotes: 3

Views: 1715

Answers (3)

cuiqiang1990
cuiqiang1990

Reputation: 19

The right code is:

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

The length of time is len(time), but the largest index of time is len(time) - 1 since the index starts from zero.

Or you can just use if time[-1] != "s": to get and judge the tail element.

Upvotes: -1

Kijewski
Kijewski

Reputation: 26033

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

Upvotes: 4

Burhan Khalid
Burhan Khalid

Reputation: 174662

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'

Upvotes: 2

Related Questions