Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a string is a palindrome?

I have a code to check whether a word is palindrome or not:

str = input("Enter the string")
l = len(str)
p = l-1
index = 0
while index < p:
    if str[index] == str[p]:
        index = index + 1
        p = p-1
        print("String is a palindrome")
        break
    else:
        print("string is not a palindrome")

If a word is inputted, for example : rotor , I want the program to check whether this word is palindrome and give output as "The given word is a palindrome".

But I'm facing problem that, the program checks first r and r and prints "The given word is a palindrome" and then checks o and o and prints "The given word is a palindrome". It prints the result as many times as it is checking the word.

I want the result to be delivered only once. How to change the code?

like image 479
Kawin M Avatar asked Aug 22 '17 18:08

Kawin M


2 Answers

Just reverse the string and compare it against the original

string_to_check = input("Enter a string")

if string_to_check == string_to_check[::-1]:
    print("This is a palindrome")
else:
    print("This is not a palindrome")
like image 95
AK47 Avatar answered Sep 18 '22 02:09

AK47


I had to make a few changes in your code to replicate the output you said you saw.

Ultimately, what you want is that the message be displayed only at the end of all the comparisons. In your case, you had it inside the loop, so each time the loop ran and it hit the if condition, the status message was printed. Instead, I have changed it so that it only prints when the two pointers index and p are at the middle of the word.

str = input("Enter the string: ")
l = len(str)
p = l-1
index = 0
while index < p:
    if str[index] == str[p]:
        index = index + 1
        p = p-1
        if index == p or index + 1 == p:
            print("String is a palindrome")
    else:
        print("string is not a palindrome")
        break
like image 45
Antimony Avatar answered Sep 22 '22 02:09

Antimony