📅  最后修改于: 2023-12-03 15:18:57.726000             🧑  作者: Mango
A palindrome is a word, phrase, number or sequence of words that reads the same backward as forward. In this Python program, we check whether a string is a palindrome or not.
def is_palindrome(string):
string = string.lower().replace(' ', '')
return string == string[::-1]
text = 'Python palindrome'
if is_palindrome(text):
print(f"{text} is a palindrome")
else:
print(f"{text} is not a palindrome")
The is_palindrome
function takes a string as an argument and returns True
if the string is a palindrome, otherwise it returns False
.
Here's how this function works:
replace
method.string[::-1]
.The text
variable contains the string that we want to check. We pass this string to the is_palindrome
function and check the returned value.
For the above program, the output will be:
Python palindrome is not a palindrome
Note that we have spaces in the input string, so we removed them before checking whether the string is a palindrome or not.
In this Python program, we learned how to check whether a string is a palindrome or not. We also saw how to convert a string to lowercase and remove spaces from it. Palindrome checking is an interesting problem that can be solved in many ways using Python.