In this tutorial, we will learn how to check whether a string is a palindrome or not in Python. We will cover the definition of a palindrome and implement a function to check if a given string is a palindrome.
A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward (ignoring spaces, punctuation, and capitalization). Examples of palindromes include 'madam', 'racecar', and '12321'.
The syntax to check if a string is a palindrome in Python is:
def is_palindrome(s):
s = s.replace(" ", "").lower()
return s == s[::-1]
We can create a function to check if a given string is a palindrome by comparing it to its reverse.
For example,
is_palindrome
that takes one parameter s
.True
, otherwise return False
.def is_palindrome(s):
s = s.replace(" ", "").lower()
return s == s[::-1]
# Check if 'Racecar' is a palindrome
result = is_palindrome('Racecar')
# Print the result
if result:
print("'Racecar' is a palindrome")
else:
print("'Racecar' is not a palindrome")
'Racecar' is a palindrome