I am reversing a string in python though I don't want to reverse the complete string. I am using str[::-1]
to reverse the string but excluding the last character.
For example: string = '0123456789'
to be reversed to string = '987654321'
.
However when the string length is 1 then problem arises with the reversing.
I simply used string=string[len(string)-2::-1]
. It works fine for string having length greater than 1. But when string length is 1, python shows some weird results.
w='0123456789'
>>> w[len(w)-2::-1]
=>'876543210' #PERFECT
>>> w[len(w)-2:0:-1]
=>'87654321' #PERFECT
>>> w[len(w)-2:-1:-1]
=>'' #WHAT? - (1)
>>> w[len(w)-2:-2:-1]
=>'' #WHAT? - (2)
>>> w[len(w)-2:-3:-1]
=>'8' #WHAT? - (3)
>>> w[len(w)-2:-4:-1]
=>'87' #WHAT? - (4)
#now see what happens when length of w is 1
>>> w='a'
>>> w[len(w)-2::-1]
=>'a' #WHAT - (5) as len(w)-2 is -1
>>> w[len(w)-2:0:-1]
=>'' #PERFECT
>>> w[len(w)-2:-1:-1]
=>'' #PERFECT as it's [-1:-1:-1]
>>> w[len(w)-2:-2:-1]
=>'a' #WHAT - (6)
>>> w[len(w)-2:-3:-1]
=>'a' #WHAT - (7)
>>> w[len(w)-2:-4:-1]
=>'a' #WHAT - (8)
when w='0123456789'
why are the lines marked WHAT - (1)
and WHAT - (2)
not showing anything while the lines marked WHAT- (3)
and WHAT - (4)
start from 8 in reverse direction? When w='a'
why are the lines marked WHAT - (5)
shows 'a'
when I am starting from -1 index and what is happening with the lines marked WHAT - (6)
, WHAT - (7)
and WHAT - (8)
?