I'm trying to split a string from the right. Following is the code.
string = "abcde"
n = len(string)
slices = [string[i-3:i] for i in range(n,0,-3)]
print (slices)
I get the output as ['cde', '']
. I'm trying to get ['cde', 'ab']
But when I split it from left it gives the proper output, i.e..,
string = "abcde"
slices = [string[i:i+3] for i in range(0,n,3)]
print (slices)
output: ['abc', 'de']
Can anyone point out where am I going wrong?
You are close. You need to floor the first indexing argument at 0:
x = "abcde"
n = len(x)
slices = [x[max(0,i-3):i] for i in range(n,0,-3)]
['cde', 'ab']
The reason your code does not work is because with positive indices, falling off the end means going as far as you can.
While negative indices means starting from the end, rather than going to the start and no further.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With