0

I found two other posts asking about this error on stack overflow but the answers weren't very helpful in providing relevant solutions. I've just started learning python and am trying to make a palindrome tester but I want it to remove all punctuation from the input. I keep getting the error in the title and I don't know how to fix it. Here is my code:

while 1:
    def reverse(text):
        return text[::-1]

    def eliminate_punc(para):
        para = para[:]
        forbidden = ('.','?','!',':',';','-','—-','()','[]','...',"'",'"','/',',',' ')
        for item in para:
            for sign in forbidden:
                if item == sign:
                    para.remove(item)
        return para

    def is_palindrome(words):
        text = eliminate_punc(words)
        return text == reverse(text)

    user_input = input("Enter text: ")

    if user_input == "quit":
        break

    if is_palindrome(user_input):
        print("\nYes, this is a palindrome")
    else:
        print("\nNo, this is not a palindrome")

    print("\nWrite 'quit' to quit the program\n")

Please help. Thanks in advance.

  • 1
    Why are you constantly redefining the functions inside the while loop? para is also obviously a string and not a list – Padraic Cunningham Jul 10 '16 at 12:14
  • 1
    `AttributeError: 'str' object has no attribute 'remove'` which part of this message you do not understand? There is no `remove` in [string methods listed in official docs](https://docs.python.org/3/library/stdtypes.html#string-methods). – Łukasz Rogalski Jul 10 '16 at 12:15
  • `return "".join([c for c in para if c not in forbidden])` will fix your problem – Padraic Cunningham Jul 10 '16 at 12:17
  • Or to save typing the `forbidden` values: `return "".join([c for c in para if c.isalpha()])` – joel goldstick Jul 10 '16 at 12:22
  • Thanks Padraic that fixed it but can you explain how the syntax works? – Manuj Mishra Jul 10 '16 at 12:28
  • The `.remove()` method will only work on mutable objects, like lists. Instead, you are dealing with the string `para`, which by definition is an immutable object. A way to make `eliminate_punc()` return a new string without *forbidden* values, is using a list comprehension: it will iterate over every character of the string and return a list of values that don't belong to the *forbidden* list. As suggested by @Padraic and @joel: `[c for c in para if not c in forbidden]`. Then you `join` the list of characters created by the list comprehension and you get the new string to return. – Daniele Barresi Jul 10 '16 at 13:08

0 Answers0