This question is not about another way to solve the problem, but about the existence of a syntax to plug a hole. I know there are many other ways to do this, but it is not what I'm interested in.
In python, you can index sequences (strings, lists or tuples) from the end with negative index value, and you can slice them using ":" inside the square brackets. for an exemple, you can use "123456789"[-4:-2]
to get "67"
. You can even use a variable :
for i in range(-4, 0):
print('"123456789"[-5:{}] yields "{}"'.format(i, "123456789"[-5:i]))
which will yield
"123456789"[-5:-4] yields "5"
"123456789"[-5:-3] yields "56"
"123456789"[-5:-2] yields "567"
"123456789"[-5:-1] yields "5678"
but what if you want to go up to the last position ? because print(0, "123456789"[-5:0])
won't do :
for i in range(-4, 1):
print('"123456789"[-5:{}] yields "{}"'.format(i, "123456789"[-5:i]))
which will yield
"123456789"[-5:-4] yields "5"
"123456789"[-5:-3] yields "56"
"123456789"[-5:-2] yields "567"
"123456789"[-5:-1] yields "5678"
"123456789"[-5:0] yields ""
One way to solve this might be to got to None
instead of 0
, in order to emulate this code : print(i, "123456789"[-5:])
for r in range(-4, 0)), [None]:
for i in r:
print('"123456789"[-5:{}] yields "{}"'.format(i, "123456789"[-5:i]))
or
for i in [ x for r in [range(-4, 0)), [None] for x in r]:
print('"123456789"[-5:{}] yields "{}"'.format(i, "123456789"[-5:i]))
which will yield
"123456789"[-5:-4] yields "5"
"123456789"[-5:-3] yields "56"
"123456789"[-5:-2] yields "567"
"123456789"[-5:-1] yields "5678"
"123456789"[-5:None] yields "56789"
but this is not a perfect solution, because None
does not mean the last position, but the default value which will depend on the sign of the step and will lead to inconsistent results if step has a negative value:
for step in 1, -1:
print("step={}".format(step))
for r in [range(-7, -0), [None,]]:
for i in r:
print('"123456789"[-4:{}:{}] yields "{}"'.format(i, step, "123456789"[-4:i:step]))
will yield
step=1
"123456789"[-4:-7:1] yields ""
"123456789"[-4:-6:1] yields ""
"123456789"[-4:-5:1] yields ""
"123456789"[-4:-4:1] yields ""
"123456789"[-4:-3:1] yields "6"
"123456789"[-4:-2:1] yields "67"
"123456789"[-4:-1:1] yields "678"
"123456789"[-4:None:1] yields "6789"
step=-1
"123456789"[-4:-7:-1] yields "654"
"123456789"[-4:-6:-1] yields "65"
"123456789"[-4:-5:-1] yields "6"
"123456789"[-4:-4:-1] yields ""
"123456789"[-4:-3:-1] yields ""
"123456789"[-4:-2:-1] yields ""
"123456789"[-4:-1:-1] yields ""
"123456789"[-4:None:-1] yields "654321"
is there another way to specify that my slice goes to the last position instead of the default position ?