Python program to check if a string is palindrome or not



Examples :

  Input:  malayalam  Output:  Yes  Input:  geeks  Output:  No 

Method # 1
1) Find Backward Line
2) Check if the reverse and the original match.

# function that returns the back string

def reverse (s):

return s [:: - 1 ]

 

def isPalindrome (s):

# Call back function

  rev = reverse (s)

 

# Check whether both strings are equal or not

if (s = = rev):

return True

return False

 

 
# Driver code

s = "malayalam"

ans  = isPalindrome (s)

 

if ans = = 1 :

  print ( " Yes " )

else :

print ( " No " )

Output:

 Yes 

Iterative Method: this method is provided by Ball Raza . Loop from start to length / 2 and check the first character to the last character of the string and the second to the second last, and so on …. If any character does not match, the string will not be a palindrome.

Below is the implementation of the above approach:

# function to check the line
# palindrome or not

def isPalindrome ( str ):

 

# Loop from 0 to len / 2

for i in xrange ( 0 , len ( str  ) / 2 ): 

if str [i]! = str [ len ( str ) - i - 1 ]:

return False

return True

 
# main function

s = "malayalam"

ans = isPalindrome (s)

 

if (ans):

print ( "Yes" )

else :

print ( "No" )

Output:

 Yes 

Method using built-in function for call lines: this method is provided by Shariq Raza . In this method, the predefined function & # 39; & # 39; .join (reversed (string)) is used to reversed a string.

Below is the implementation of the above approach:

# function to check the string
# palindrome or not

def isPalindrome (s):

 

# Using a predefined function for

# revert to line output

rev = `` .join ( reversed ( s))

 

  # Check if both lines are

# equal or not

if (s = = rev):

return True

return False

 
# main function

s = "malayalam"

ans = isPalindrome (s)

 

if (ans):

print ( "Yes" )

else :

print ( "No" )

Output:

 Yes 

Method using one additional variable: In this method, the user takes a string character one by one and stores it in an empty variable. After saving all characters, the user compares both strings and checks if it is a palindrome or not.

# Python program to check
# if the string is a palindrome
# or not

 

x = "malayalam"

w = ""

for i in x:

  w = i + w

  if (x = = w):

print ( " YES " )

 

Exit :

 Yes 

This article is courtesy of Sahil Rajput . If you are as Python.Engineering and would like to contribute, you can also write an article using contribute.python.engineering or by posting an article contribute @ python.engineering. See my article appearing on the Python.Engineering homepage and help other geeks.

Please post comments if you find anything wrong or if you would like to share more information on the topic discussed above.