1

I'm really confused now:

>>> string = "some string"
>>> string[100:105]
''
>>> string[100]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: string index out of range

Why does string[100:105] return an empty string whereas string[100] raises an IndexError (as expected)? Why does string[100:105] not raise an IndexError as well?

6q9nqBjo
  • 161
  • 7

2 Answers2

1

When slicing a string in Python, the string[100:105], the operation was designed specifically to fail gracefully. The result of an out of range slice is to return the empty string ''. See the Informal Introduction for more information.

Accessing a specific index of a string, the string[100] was not designed to fail gracefully, so it raise an exception.

Tague Griffith
  • 3,963
  • 2
  • 20
  • 24
0

String slicing in python will not raise errors, they will just return the string that you were looking for (in this case, it's indeed a empty string because there's nothing there).

Slicing returnes a subsequence of items, and it doesn't do any bound checking. If the wanted data (memory) is empty, it will send back an empty string as you got.

Ofer Arial
  • 1,129
  • 1
  • 10
  • 25