-1

I wrote a short script to tell me if a phrase taken in by a user is a palindrome or not, and I'm wondering how I can shorten my current code.

Here is the current code:

def palindrome():
    string = input()
    stringremove = string.replace(" ", "")
    
    if stringremove[0] == stringremove[-1]:
        if stringremove[1] == stringremove[-2]:
            if stringremove[2] == stringremove[-3]:
                if stringremove[3] == stringremove[-4]:
                    print("It's a palindrome!")
                else:
                    print("It's not a palindrome!")
            else:
                print("It's not a palindrome!")
        else:
            print("It's not a palindrome!")
    else:
        print("It's not a palindrome!")
              
palindrome()

Obviously I could keep going for longer and longer phrases / words, but I'm thinking there is an easy way to get around this with much shorter code.

2 Answers2

3

Generally speaking, what you are looking for are loops, best to search for python docs loops.
Here is a quick answer to your specific question:

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

This checks whether s is a palindrome. In your case, invoke it as follows:

string = input()
stringremove = string.replace(" ", "")
if is_palindrome(stringremove): print("It's a palindrome!")
else: print("It's not a palindrome!")

Note, that this way the input and preprocessing has been moved out of the function, making it more versatile.

As for the palindrome function itself, there is an even shorter way in python, to simply reverse the string (s[::-1], see Python slicing for details) and check whether the strings are equal:

def is_palindrome(s):
  return s == s[::-1]
Tom
  • 749
  • 4
  • 16
2

try:

def palindrome(string : str):
    newstring = string.replace(" ", "") # removes Whitespace (so you can do 'taco cat' palindrome)
    newstring.lower()
    if newstring == newstring[::-1]: # [::-1] reverses string
        print("It's a palindrome!")
    else:
        print("It's not a palindrome!")