3

Say you have a string named s:

s = "000000000000000000000000000000000000000000000000000000000000000"
len(s)
#63

When you run s[64:], the Python compiler returns ''.
However, when you run s[64] the code raises the following error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: string index out of range

Why does this happen?
Thanks in advance.

NRO
  • 76
  • 7
  • Sidenote, `str` is a bad name cause it shadows the builtin `str` type. You could use `s` or `string` instead. C.f. [TypeError: 'list' object is not callable](https://stackoverflow.com/q/31087111/4518341) – wjandrea Apr 16 '21 at 21:37
  • Mostly, programmer convenience. Most seemingly invalid slices return valid empty results, like `str[9:5]`. Direct references to an element, on the other hand, are usually a programming error and should be caught. – Tim Roberts Apr 16 '21 at 21:38
  • 2
    For this string, the slice `64:` is an empty slice, which is not required to be anchored within the string. `64` by itself, on the other hand attempts to reference a single element of the string that does not exist, which is an error. Also, you should avoid using `str` as a variable name, since that will mask the default definition of `str`. – Tom Karzes Apr 16 '21 at 21:39
  • [This](https://stackoverflow.com/a/9490148/4518341) is my favourite answer to this question, and [this one](https://stackoverflow.com/a/42680568/4518341) is rigorous. – wjandrea Apr 16 '21 at 21:49

0 Answers0