Check if a String is a Palindrome in Python
"Every text string hides patterns, and palindromes remind us that symmetry also has its own logic in programming."
A string palindrome is a word or phrase that reads the same from left to right and from right to left.
Some common examples are:
"oso"
(Spanish for "bear")"radar"
"anita lava la tina"
(Spanish phrase, palindrome)
In this tutorial, you will learn how to detect if a string is a palindrome in Python using different methods.
Method 1: Using slicing in Python
Python allows you to reverse strings easily with [::-1]
.
This is the simplest and most direct method.
def is_palindrome(text: str) -> bool:
text = text.lower().replace(" ", "")
return text == text[::-1]
print(is_palindrome("radar")) # True
print(is_palindrome("python")) # False
print(is_palindrome("Anita lava la tina")) # True
Advantages:
- Very short and easy to read.
- Ideal for quick exercises and interviews.
Method 2: Using a for loop
If you want to do it without shortcuts, you can compare each character of the string with its counterpart from the end.
def is_palindrome_loop(text: str) -> bool:
text = text.lower().replace(" ", "")
for i in range(len(text) // 2):
if text[i] != text[-i - 1]:
return False
return True
print(is_palindrome_loop("oso")) # True
print(is_palindrome_loop("hola")) # False
Advantages:
- Helps you understand how indexes work.
- Useful to grasp the logic behind the problem.
Method 3: Using the reversed()
function
Another alternative is to reverse the string with reversed()
and then join the characters.
def is_palindrome_reversed(text: str) -> bool:
text = text.lower().replace(" ", "")
return text == "".join(reversed(text))
print(is_palindrome_reversed("radar")) # True
Important considerations
- It’s best to normalize the text: convert to lowercase and remove spaces.
- If accents or special characters are included, you can use
unicodedata
to normalize them. - This makes the algorithm more robust for longer phrases.
You may also be interested in: