简体   繁体   中英

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

Indexes in Python begin with 0 , ie 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.

Cf http://www.tutorialspoint.com/python/python_lists.htm

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'

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM