'If myStr = 'test', why does myStr[4] produce error out of range but myStr[4:] does not?
I'm using recursion to iterate through the values of a string. When I get past the last character, it's allowing me to use that index position as an empty string ""
instead of giving an error. Why is that?
myStr = 'test'
print(myStr[4])
produces an error
print(myStr[4:])
does not produce any error.
Solution 1:[1]
Slicing is not bounds-checked by the built-in types. If the array indices are out of bounds, it will automatically truncate then at the right places.
Solution 2:[2]
Because array accesses are defined such that it's an error for a lone index to be out of range, but not for (part or all of) a slice to be. If any part of a slice is out of range, it simply yields no results, rather than triggering an error.
Solution 3:[3]
Because that's how the language was designed. Python 3.0 documentation says about strings that
Attempting to use an index that is too large will result in an error. However, out of range slice indexes are handled gracefully when used for slicing.
word = 'test'
>>> word[4] # the word only has 4 characters
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: string index out of range
>>> word[2:4]
'st'
>>> word[4:]
''
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Mark Reed |
Solution 3 |