首页 > 解决方案 > Index a string slice from it's end with a variable in python doesn't provide generic acces to last element

问题描述

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 ?

标签: pythonsequenceslice

解决方案


如果 slice 中的 stop 值大于等于字符串的长度,则默认设置为字符串的长度。

"123456789"[-5:len('123456789')]也产生'56789'


推荐阅读