String slicing returning unexpected values

Viewed 62

I hope this is a simple question! I am trying to reverse a number, and be given the digits in the 'even' positions. When I try to do this within one string slice, I am just given a single digit, even when I am expecing more. When I do it as two slices, I am given the correct answer, but I am unsure why.

For example, if I have the number 512341234, I would expect it to give me 3131, as I have first reversed the string (432143215) and then taken the even position numbers (4[3]2[1]4[3]2[1]5).

Below is the code which I have tried to use to make it work, but doing it as one slice only returns the single digit, whereas doing it as two means it returns the expected value. Why is this?

num = 512341234
str(num)[1::-2] #returns 1
str(num)[::-1][1::2] #returns 3131

Thanks! Noah

1 Answers

1::-2 means to start at position 1 (the second character) and go backwards two characters at a time. You want to start somewhere near the end of the string, e.g.

num = 512341234
str(num)[-1::-2]
'42425'
num = 512341234
str(num)[-2::-2]
'3131'

But you’ll have to pick -1 or -2 based on which one of those characters is in an even position (i.e. based on the length of the string) to do this.

Related