OneBite.Dev - Coding blog in a bite size

check if a string is a palindrome in python

Code snippet on how to check if a string is a palindrome in python

  def is_palindrome(my_string):
  # remove whitespaces
  my_string = my_string.replace(" ", "") 
  # check if string and its reverse are same
  if my_string == my_string[::-1]: 
    return True
  return False

This code checks if a given string is a palindrome or not. First, it removes all the whitespaces from the user-supplied string. Then, it compares the given string and its reverse to see if they are the same or not. If both strings match, the function returns true, otherwise, it returns false. To reverse a string, the code uses slicing - my_string[::-1]. This creates a reversed copy of the string using a technique that starts from the end of the string and reads it backwards until the start. Finally, the comparison evaluates whether the original string is equal to its reversed copy. If both strings are equal, the given strings is a palindrome.

python