0

For some reason string.replace(" ", "") is not working. Is there another way of removing white spaces from a string? Why is .replace not working in this particular situation?

string = input('enter a string to see if its a palindrome: ')
string.replace(' ', '')  # for some reason this is not working 
                         # not sure why program will only work with no spaces
foo = []
bar = []

print(string)
for c in string:
    foo.append(c)
    bar.append(c)

bar.reverse()
if foo == bar:
    print('the sentence you entered is a palindrome')
else:
    print('the sentence you entered is not a palindrome')
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
  • 1
    strings are not mutable. `str.replace()` produces a *new* string object, but you are ignoring the return value. – Martijn Pieters Jul 15 '16 at 07:11
  • As a side note, you can use slice notation to make this alot easier. Something like this will tell you if you have a palindrome `if string == string[::-1]: ` – Keatinge Jul 15 '16 at 07:17

1 Answers1

5

replace() returns a new string, it doesn't modify the original. Try this instead:

string = string.replace(" ", "")
Josh Smeaton
  • 47,939
  • 24
  • 129
  • 164