how to check if the string is pallindrome or not in python??

## All 14 Replies

There is no built in function that I know of to check that.

On thing you might try doing is reversing the string and then comparing each element.

``````inString = 'racecar'
reversestring = ''
for i in range(0,len(inString)-1:
reversestring.append(inString[i]``````

Another way to do it would be to compare the first element to the last element in your string and make sure they match the whole time. One thing that is helpful to remember when doing this is that string[-1] will give you the last element of the string, and string[-2] will give you the second to last. So if your string is racecar then inString[0] should equal inString[-1] and inString[1] should equal inString[-2] etc.

there are a couple of posts regarding palindromes in the forum, have a look around.... but basically the algorithm is what mn_kthompson suggested :)

Thank you very much!!
It was helpful. But how could we test if the given string is pallindrome or not. I need a syntax that returns true if the string is pallindrome otherwise false.

just compare the inString with reversestring using the == operator

But how could we test if the given string is pallindrome or not. I need a syntax that returns true if the string is pallindrome otherwise false.

``````>>> def is_palindrome(s):
...     return s.lower() == s[::-1].lower()
...
>>> is_palindrome('test')
False
>>> is_palindrome('racecar')
True
>>> is_palindrome('RACECAR')
True``````
commented: Very elegant solution to palindrome problem +2

bravo!!! snipsat.
Dint know something like this exists in Python.

or you could do it using a loop:

``````def isPalindrome( s ):
s = s.lower()
for i in range( len ( s ) / 2 ):
if s[ i ] != s[ -1 -i ]:
return False
return True

>>> isPalindrome( "RACECAr" )
True
>>> isPalindrome( "test" )
False
>>> isPalindrome( "civiC" )
True
>>> isPalindrome( "ciniC" )
True
>>> isPalindrome( "cinac" )
False
>>>``````

:)

Let's hope this is not homework and the OP had a chance to learn something.

In a true palindrome test you also need to remove everything but the case adjusted letters.

IT was quite helpful. so in case of palindromes how can we remove the symbols and capital letters using .upper and replace function?? for example

IT was quite helpful. so in case of palindromes how can we remove the symbols and capital letters using .upper and replace function?? for example

Use replace to swap out the punctuation for an empty string (''). Then use upper on both the original and the reversed string when you compare them so that the cases are the same.

Here are a few things you can do with Python ...

``````s = "Madam, in Eden I'm Adam!"

new = ""
for c in s:
if c.isalpha():
new += c

# convert all characters to lower case
new = new.lower()

# reverse new
new_rev = ''.join(reversed(new))

print(new == new_rev)  # True``````

The code can be made shorter, but than it isn't quite as readable for a beginner.

First of all, bravo to snippsat for a very elegant solution. I have never seen string splicing like that.

Now, how to remove the spaces and symbols? Well there is the easy inefficient way and the efficient but more difficult way.
The easy but inefficient way would be to loop through each character in the string and test if it is a space, tab, period, comma, etc. If so, then move on to the next character. If it is not one of those, then write it to a temporary string. Then test the temporary string to see if it is a palindrome and return true or false.

The problem with this method is that you're going to have a lot of if statements that you'll need to maintain. You would have to have an if statement for every symbol and non printable character on your keyboard...not to mention international symbols too. You would also run every character through a ton of tests that most likely wont apply so your code will be less efficient and more difficult to maintain. On the other hand, if this is an assignment for an entry level class this is probably all that is expected of you at this point.

The more efficient way of doing it would be to test each character against a regular expression of characters that you're interested in. If the character is in the range of a-z then copy it to a temporary string. If not, then pass on to the next character. Now you only have to maintain one if statement instead of a quadrillion. It will be more effective because it looks for a list of known acceptable characters rather than trying to list every character you're not interested in, and you will only perform one test on each character which makes your code more efficient.

``````mystring = 'A man, a plan, a canal, panama.'

# first, establish a temporary string and strip out the unwanted
# characters
tempstring = ""
for char in mystring.lower():
if re.match("[a-z]", char):
tempstring += char

# then use the techniques described above to test for palindrome.
return tempstring == tempstring[::-1]``````

Or you could use isalpha() like vegaseat did and stop being a chode like me.

You can also do this without a loop

``````#!/usr/bin/env python
import re

nonletters = re.compile("[^a-zA-Z]+")

def letters_only(mystring):
return nonletters.sub(lambda m: '', mystring)