search

How to check if a string is a palindrome in Python?

A string is a palindrome if it reads the same forwards as backwards. In Python, you can check if a string is a palindrome by comparing the original string with its reverse.

One way to do this is by using slicing:

def is_palindrome(string):
    return string == string[::-1]

print(is_palindrome("racecar"))  # Output: True
print(is_palindrome("hello"))  # Output: False

Another way is to use the **reversed** function and convert the reversed string back to a list or string using the **join** or **list** method:

def is_palindrome(string):
    return list(string) == list(reversed(string))

print(is_palindrome("racecar"))  # Output: True
print(is_palindrome("hello"))  # Output: False

Related Questions You Might Be Interested