How do I check if a string is a palindrome in Python?
Davide S
davide s profile pic

To check if a string is a palindrome in Python, you can use various methods. A palindrome is a word, phrase, number, or sequence of characters that reads the same forward and backward. Here's a detailed explanation of a few commonly used methods: Method 1: Using String Reversal One approach is to reverse the string and compare it with the original string. If they are the same, the string is a palindrome.

1
2
3
4
5
6
7
8
9
10
11
12
13
14

def is_palindrome(string):
    reversed_string = string[::-1]
    if string == reversed_string:
   return True
    else:
   return False

word = "radar"

if is_palindrome(word):
    print("The word is a palindrome.")
else:
    print("The word is not a palindrome.")

In this example, theis_palindrome() function takes a string as input, reverses it using string slicing ([::-1]), and compares it with the original string. If they are the same, the function returnsTrue, indicating that the string is a palindrome. Method 2: Using Iteration Another approach is to iterate over the string and compare the characters from both ends. If all characters match, the string is a palindrome.

1
2
3
4
5
6
7
8
9
10
11
12
13
14

def is_palindrome(string):
    length = len(string)
    for i in range(length // 2):
   if string[i] != string[length - i - 1]:
  return False
    return True

word = "radar"

if is_palindrome(word):
    print("The word is a palindrome.")
else:
    print("The word is not a palindrome.")

In this example, theis_palindrome() function iterates over the string up to half its length. It compares the characters at corresponding positions from both ends. If any characters don't match, the function returnsFalse, indicating that the string is not a palindrome. If all characters match, it returnsTrue. Method 3: Using Recursion You can also use recursion to check if a string is a palindrome by comparing the first and last characters, then recursively checking the substring between them.

1
2
3
4
5
6
7
8
9
10
11
12
13
14

def is_palindrome(string):
    if len(string) <= 1:
   return True
    if string[0] == string[-1]:
   return is_palindrome(string[1:-1])
    return False

word = "radar"

if is_palindrome(word):
    print("The word is a palindrome.")
else:
    print("The word is not a palindrome.")

In this example, theis_palindrome() function uses recursion to check if the first and last characters of the string match. If they do, it calls the function again with the substring between them (string[1:-1]). This process continues until the length of the substring is less than or equal to 1. If all comparisons are successful, the function returnsTrue. These are some of the methods to check if a string is a palindrome in Python. Choose the method that best suits your needs based on the specific conditions you need to handle.