3

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

Lafexlos
  • 7,618
  • 5
  • 38
  • 53
nikodem363
  • 33
  • 4

3 Answers3

4

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

Community
  • 1
  • 1
Kijewski
  • 25,517
  • 12
  • 101
  • 143
  • You're welcome! Next to all programming languages have zero-based indexes. Of the languages I know only Pascal/Delphi and Matlab use 1-based indexes. The rationale is that the calculation is much easier to do in a 0-based system. – Kijewski Dec 29 '15 at 05:02
2

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'
Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
-1

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.