1

I made a function to check if string is a palindrome

It is suppose to replace anything in the string that is not an alphabet with '' but the replace() method isn't working

alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
            'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']


def is_palindrome(text):
    word = text.lower()

    for l in word:
        if l not in alphabet:
            word.replace(l, '')

    return word == text[::-1]


print(is_palindrome('Rise to vote, sir.'))

I expect the output of True but the actual output is False

1030
  • 41
  • 6

2 Answers2

3

Reassign it.

# word.replace(l, ''): the result of the function is a string,
# so you must reassign
word = word.replace(l, '')
HK boy
  • 1,398
  • 11
  • 17
  • 25
3

To expand on HK boy's answer (and because I don't have enough reputation to comment), the replace method doesn't modify the existing string, it returns a new string. You have to assign it to a variable (or the same variable) in order to use the string with the replaced characters.

word = word.replace(l, '')
samm82
  • 240
  • 4
  • 14