Table of Contents

Check Palindrome String Python

Example Description
Learn how to check if a string is a palindrome or not in Python. Use the checkPalin function to validate if a given string is a palindrome.

Introduction:

This code checks whether a given string is a palindrome or not. A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward. The logic of the code is to compare the characters at the beginning and end of the string and move towards the center, checking if they are equal. The output of the code will tell you whether the given string is a palindrome or not.

Code:

#Function to check if a string is palindrome or not
def checkPalin(st):
 i = 0
 j = len(st) - 1
 while(i <= j):
  if(st[i] != st[j]):
    return False
  i += 1
  j -= 1
 return True
#end of function
st = input("Enter a String: ")
result = checkPalin(st)
if result == True:
 print("The given string",st,"is a palindrome")
else:
 print("The given string",st,"is not a palindrome")

Logic:

  1. Define a function called “checkPalin” that takes a string as input.
  2. Initialize two variables, “i” and “j”, to keep track of the two ends of the string.
  3. Use a while loop to iterate until “i” is less than or equal to “j”.
  4. Inside the loop, check if the character at index “i” is not equal to the character at index “j”. If they are not equal, return False, indicating that the string is not a palindrome.
  5. If the characters are equal, increment “i” and decrement “j” to move towards the center of the string.
  6. If the loop completes without returning false, it means that the string is a palindrome. Return True.
  7. End the function.
  8. Prompt the user to enter a string.
  9. Call the “checkPalin” function with the input string and store the result in the “result” variable.
  10. Check if the “result” is True. If it is, print that the given string is a palindrome. If not, print that the given string is not a palindrome.

Output:

>> Enter a String: noon

>> The given string noon is a palindrome

>> Enter a String: racecar

>> The given string racecar is a palindrome