1

I want to find a palindrome in a string.

mystring = "1234321"

Why does

mystring[3:7:-1] 

not work, but

second = mystring[3:7]
reversed = second[::-1]

this work?

3 Answers 3

7

Because you have to tell python to "start" with the end index and "end" with the start index:

>>> "0123456789"[7:3:-1]
'7654'
Sign up to request clarification or add additional context in comments.

1 Comment

In the case of the OP's example, mystring[6:2:-1]
0

When you reversing the string on the fly like that, you need to put the larger index first. You should use:

mystring[7:3:-1]

instead of:

mystring[3:7:-1]

Comments

0

mystring[::-1] implies the start and the end.

Using [3:7:-1] you give an "increment", start index and finish index, but you are also instantly out of your string boundaries....

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.