I have a code to check whether a word is palindrome or not:
JavaScript
x
13
13
1
str = input("Enter the string")
2
l = len(str)
3
p = l-1
4
index = 0
5
while index < p:
6
if str[index] == str[p]:
7
index = index + 1
8
p = p-1
9
print("String is a palindrome")
10
break
11
else:
12
print("string is not a palindrome")
13
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?
Advertisement
Answer
Just reverse the string and compare it against the original
JavaScript
1
7
1
string_to_check = input("Enter a string")
2
3
if string_to_check == string_to_check[::-1]:
4
print("This is a palindrome")
5
else:
6
print("This is not a palindrome")
7