-1

I am trying to check if a string that is passed in to a function is a palindrome of the second string that is passed in. Google defines a palindrome to be a word that is the same spelled forwards or backwards.

def palindrome(strA, strB):
  if (strA == strB and strA[::1] == strB):
    print "true"
  else:
    print "false"


if __name__ == '__main__':
  palindrome("sirap", "paris")

In the code above, I am attempting to check if the given string is equal to the second string both forwards and backwards yet the test i give it in main returns false. Any ideas on what im missing?

machinebit
  • 355
  • 3
  • 6
  • 17
  • 2
    `strA[::1]` is the same as `strA`. You want `strA[::-1]` – vaultah Mar 09 '16 at 17:06
  • 1
    What is a string that is palindrome of another one? As far as I know a string is palindrome if it's the same string backwards – Mr. E Mar 09 '16 at 17:08
  • Possible duplicate of [check-string-for-palindrome](http://stackoverflow.com/questions/4138827/check-string-for-palindrome/) – goodguy5 Mar 10 '16 at 19:16

2 Answers2

4

You check if 'sirap' is the same as 'paris' as well as checking if reversed 'sirap' is the same as 'paris'. You just have too many things in your if:

if strA[::-1] == strB:
    print "true"
else:
    print "false"

What you had would work if you passed in a palindrome as well as its reverse, the same thing. For example, palindrome("stats", "stats") would print "true", but I don't think that's what you had in mind. You will also notice that I used strA[::-1] instead of strA[::1]. That is because strA[::1] starts at the beginning and goes to the end, but you want to go backwards, so you should use -1.

You could even do it in one line:

print ("false", "true")[str[::-1] == strB]
zondo
  • 19,901
  • 8
  • 44
  • 83
1

I did a similar test using the "100 projects" to learn python (useful for learning any language)

You could do something like this, and just run the script. For this I just made some changes to the original palindrome script I wrote.

print "This will check if its a palindrome"
inputstring = raw_input("String1: ")
inputstring2 = raw_input("String2: ")
inputstring = inputstring.lower()
inputstring2 = inputstring.lower()
revstring = inputstring[::-1] #Reverses the string

if revstring == inputstring2:
    print "Yes: " + revstring
else:
    print "No: " + revstring
Tyler C
  • 573
  • 5
  • 17