Python Programs | IT Developer
IT Developer

Python Programs



Share with a Friend

Python Programs - String

Check if a string is a palindrome - Python Program

Example 1 :

def is_palindrome(s): s = s.replace(" ", "").lower() return s == s[::-1] print(is_palindrome("Madam"))

Output

 
OUTPUT  :
True

Example 2 : Using While Loop (strings)

string = input("Enter a String : ") length = len(string) i = 0 j = length - 1 while i < j: if string[i] != string[j]: print(string, "is not a palindrome string") break i += 1 j -= 1 else: print(string, "is a palindrome string")

Output

 
OUTPUT  :
Enter a String : madam
madam is a palindrome string

Example 3 : Using String Slicing

def is_palindrome(string): # Step 1: Convert the string to lower case string = str(string).lower() # Step 2: Reverse the string using slicing reversed_str = string[::-1] # Step 3: Compare the original and reversed strings if string == reversed_str: return True else: return False # Input a String string = input("Enter a String : ") if is_palindrome(string): print(f"{string} is a palindrome number.") else: print(f"{string} is not a palindrome number.")

Output

 
OUTPUT  :
Enter a String : Madam
Madam is a palindrome number

Example 4 : Using Character matching

def is_palindrome(string): # Convert the string to lower case string = string.lower() # Iterate from the start to the middle of the string for i in range(len(string) // 2): # Compare characters from the start and end if string[i] != string[len(string) - 1 - i]: # If any characters don't match, it's not a palindrome return False # If all characters match, it's a palindrome return True # Input a String string = input("Enter a String : ") if is_palindrome(string): print(f"{string} is a palindrome number.") else: print(f"{string} is not a palindrome number.")

Output

 
OUTPUT  :
Enter a String : Malayalam
Malayalam is a palindrome number.