That is simply because how indexing works in Python.
s[-1: -9: -1] has 8 characters just like s or s[0: 9: 1] has 8 characters. The last index is always ignored. This is done so that things like range(n) have, like the call suggests, n terms although it goes from 0 to n-1.
It is clearer if you forget numbers altogether and just look at this object: s[0: len(s): +1]. Reverse the sign of the indexes and substract -1 to get the opposite string s[-0-1: -len(s)-1: -1].
That is simply because how indexing works in Python.
s[-1: -9: -1] has 8 characters just like s or s[0: 9: 1] has 8 characters. The last index is always ignored. This is done so that things like range(n) have, like the call suggests, n terms although it goes from 0 to n-1.
It is clearer if you forget numbers altogether and just look at this object: s[0: len(s): +1]. Reverse the sign of the indexes and substract -1 to get the opposite string s[-0-1: -len(s)-1: -1].
In python, slicing can be used to get the sub-section of the Object.
- len(S) - return the length of the string.
- S[index] - get the character at a particular index from the start. positive index.
- S[-index] - get the character at a particular index from the end. negative index.
- S[start:end] - slice the string from a start index to an end position not index.
- S[start:] - slice the string from a start index to the last position.
- S[:end] - slice the string from 0 indexes to the end position.
- S[:] - get the whole string like copy the string.
- S[i:j:k] - slice the string with step. default k is +1. like s[2:10:2]
- s[::-1] - reverse the string.
Your call tell rfind to start looking at index 34. You want to use the rfind overload that takes a string, a start and an end. Tell it to start at the beginning of the string (0) and stop looking at index:
>>> s = "Hello, I am 12! I like plankton but I don't like Baseball."
>>> index = 34 #points to the 't' in 'but'
>>> index_of_2nd_I = s.rfind('I', 0, index)
>>>
>>> index_of_2nd_I
16
I became curious how to implement looking n times for string from end by rpartition and did this nth rpartition loop:
orig = s = "Hello, I am 12! I like plankton but I don't like Baseball."
found = tail = ''
nthlast = 2
lookfor = 'I'
for i in range(nthlast):
tail = found+tail
s,found,end = s.rpartition(lookfor)
if not found:
print "Only %i (less than %i) %r in \n%r" % (i, nthlast, lookfor, orig)
break
tail = end + tail
else:
print(s,found,tail)
Why does [::1] reverse a string in Python?
iterate over a string in reverse
Videos
For example:
txt = "Hello World"[::-1]
Isn't the splice syntax [start : stop: step]? And default of start and stop are the beginning and end of the string? So that would make the above start at the beginning, stop at the end, but step by -1. That feels like it would start at the beginning, then step backwards to...before the beginning of the string?
Sorry for the silly question, I just can't figure out why this syntax works the way it does.