📜  python palindrome - Python (1)

📅  最后修改于: 2023-12-03 15:18:57.726000             🧑  作者: Mango

Python Palindrome

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.

Program
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")
Explanation

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:

  1. Convert the string to lowercase so that we can compare it with its reverse case-insensitively.
  2. Remove all the spaces from the string using the replace method.
  3. Check whether the string is equal to its reverse using the Python slicing notation 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.

Output

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.

Conclusion

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.