How to Check Whether a String is a Palindrome Using Python

Checking for a palindrome string in python is trivial due to built-in functions and powerful string indexing and slicing. The following python program checks whether a string input by user is a palindrome,

input_str = input("Please enter a string: ").lower()
if input_str == input_str[::-1]:
    print("{} is a palindrome".format(input_str))
else:
    print("{} is NOT a palindrome".format(input_str))

Even though the above code is small, it does demonstrate a number of powerful python features,

  • The input is converted to lowercase using the lower() function of string. This is for case insensitive comparison for palindromes.
  • The input is compared to the reversed string. To reverse the string we use the slicing of the string. The slice takes 3 parameters – start index, end index and a step. Since start and end are not specified, it means the entire string and -1 for step indicates slicing backwards from the start index. This wraps around to the beginning of the string. The end result is that you get the reversed string.

The following python program achieves the same thing using lists and reversed() built-in function. The reversed() function returns a reversed iterator for the input sequence. We pass it to the list() function to get a list of characters. If it is same as the list of characters from the original string, we have a palindrome.

input_str = input("Please enter a string: ").lower()

if list(input_str) == list(reversed(input_str)):
    print("{} is a palindrome".format(input_str))
else:
    print("{} is NOT a palindrome".format(input_str))

Do you have a programming problem that you are unable to solve? Please send us your problem and we will publish the solution! Please email us.

Leave a Reply