0

This is a question about syntax more than anything. I am pretty sure that I am almost right, but not quite. I'm trying to put a for loop inside of the expression for an if statement.

A mock-up of what I think it should be for a simple palindrome tester:

toTest = "asdffdsa"
if toTest[i]==toTest[-i] for i in range(len(toTest)/2):
    print("It's a palendrome!")

Thanks in advance for your help!

2

2 Answers 2

7

I guess you mean

if all(toTest[i] == toTest[-i] for i in range(len(toTest)/2)):
    print("It's a palindrome!")

Note that it would be much easier to do

if toTest == toTest[::-1]:
    print("It's a palindrome!")
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! You just answered my question AND taught me a new keyword. Does the "-1" in "toTest[::-1]" reverse the list?
@Mokolodi1: Yes, it reverses the string, see stackoverflow.com/a/3705676/279627.
Not a keyword; all is a function.
1

While it may not be exactly what you're looking for, here is a short-hand to check if a string is a palindrome in Python:

toTest = "asdffdsa"
if toTest == toTest[::-1]: print ("It's a palindrome!")

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.