This was a HW problem in edX that asked me to determine how many times the word "bob" occurred within some string. I got to a solution, but I'm confused as to why it works. For code(1):
CODE(1)
s = 'azcbobobegghakl'
count = 0
for i in range(len(s)):
if s[i:i+3] == "bob":
count += 1
print(count)
In the same HW, there was a problem that asked me to find the longest sub-string in alphabetical order within some string. In the beginning of finding the solution, I was faced with an index error because I was trying to refer to an index that was out of range; shown in this code:
CODE(2)
s = 'azcbobobegghakl'
temp = ''
longest = ''
for i in range(len(s)):
if s[i] <= s[i+1]:
temp += s[i+1]
if len(temp) > len(longest):
longest = temp
else:
temp = s[i+1]
print(longest)
ERROR(2)
Traceback (most recent call last):
File "C:/Users/vchi/PycharmProjects/edX/introduction.py", line 5, in <module>
if s[i] <= s[i+1]:
IndexError: string index out of range
Why is it that CODE(1) is not faced with the the same kind of error that CODE(2) received when i > len(s)-4 and s[i:i+3] tries to refer to things that are out of bounds? Thank you in advance!
Python slicing is weird in a lot of ways, and this is one that kind of proves this.
With strings in python if the slice goes out of range, it will just set the "end" of the slice as the last viable index so if we did something like:
a = 'boboabcdef'
and then did:
b = a[4:12]
we would just get b is equal to 'abcdef', as it would just disregard the rest of the string.
But when it comes to indexes for lists, python has a much stricter interpretation, as it would be incredibly difficult to debug a program where a list could go out of index with no errors or warnings.