Search code examples
pythonpalindromespacesremoving-whitespace

Removing Spaces in Python not working


I am trying to remove spaces. I have tried everything from previous threads including re.sub

Code:

wordinput = (input("Input:\n"))
wordinput = wordinput.lower()
cleanword = wordinput.replace(" ","")
cleanword = wordinput.replace(",","")
cleanword = wordinput.replace(".","")
revword = cleanword [::-1]
print(cleanword)
print(revword)
print("Output:")
if (cleanword == revword):
    print('"The word ' + wordinput + ' is a palindrome!"')
else:
    print('"Unfortunately the word ' + wordinput + ' is not a palindrome. :(')

Output:

Input:
mr owl ate my metal worm 
mr owl ate my metal worm
mrow latem ym eta lwo rm
Output:
"Unfortunately the word mr owl ate my metal worm is not a palindrome. :(

Solution

  • Did you try something like:

    import re
    cleanword = re.sub(r'\W+', '', wordinput.lower())