Python Programs | IT Developer
IT Developer

Python Programs



Share with a Friend

Python Programs - Functions

Function to check if a string is a palindrome - Python Program

Method 1:

Example 1 :

def is_palindrome(s): """Check if string is palindrome.""" s = s.lower().replace(" ", "") return s == s[::-1] print(is_palindrome("Madam"))

Output

 
OUTPUT  :
True

Method 2: Using the reverse and compare method

In this case, the string is reversed and is compared with the original string. If it matches, it is Palindrome otherwise NOT.

Example 2 :

#Define a function def isPalindrome(string): if (string == string[::-1]) : return "The string is a palindrome." else: return "The string is not a palindrome." #Enter input string string = input ("Enter string: ") print(isPalindrome(string))

Output

 
OUTPUT 1 :
Enter string: MADAM
The string is a palindrome.

OUTPUT 2 :
Enter string: Madame
The string is not a palindrome.

Method 3: Using for loop

In this case, the for loop is used to iterate each character in the given string to join it with each element stored in an empty variable. If it matches, it is Palindrome otherwise NOT.

Example 3 :

#Enter input string str=input("Enter string : ") #Declare an empty string variable revstr="" #Iterate string with for loop for i in str: revstr = i + revstr print("Reversed string : ",revstr) if(str == revstr): print("The string is a palindrome.") else: print("The string is not a palindrome.")

Output

 
OUTPUT 1 :
Enter string : RADAR
Reversed string :  RADAR
The string is a palindrome.

Method 4: Using a while loop

In this case, a while loop is used to extract characters and store in an array in a reverse way. After that, it is comapred with the original string. If it matches, it is Palindrome otherwise NOT.

Example 4 :

#Define a function def isPalindrome(string): string = string.lower().replace(' ', '') first, last = 0, len(string) - 1 while(first < last): if(string[first] == string[last]): first += 1 last -= 1 else: return "The string is not a palindrome." return "The string is a palindrome." #Enter input string str1 = input("Enter string : ") print(isPalindrome(str1)) #Returns True

Output

 
OUTPUT 1 :
Enter string : RADAR
Reversed string :  RADAR
The string is a palindrome.