English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this program. You will learn to check if a string is a palindrome
To understand this example, you should understand the followingPython programmingTopic:
A palindrome is a string that reads the same forwards or backwards.
For example, 'dad' is the same in either direction. Another example is 'aibohphobia', which is a literal fear of palindromes.
# Program to check if a string is a palindrome my_str = 'aIbohPhoBiA' my_str = my_str.casefold() # Reverse the string rev_str = reversed(my_str) # Check if the string is equal to its reverse string if list(my_str) == list(rev_str): print("This string is a palindrome.") else: print("This string is not a palindrome.")
Output result
This string is a palindrome.
Note:To test the program, please change the value of my_str in the program.
In this program, we use the string stored in my_str.
By using the casefold() method, we make it suitable for unconditional comparison. Essentially, this method returns the lowercase version of the string.
We use the built-in function reversed() to reverse the string. Since this function returns a reversed object, we use the list() function to convert them to a list before comparison.