尝试删除 python .replace 中的空格不起作用

0 python string replace

由于某种原因 string.replace(" ", "") 不起作用。还有另一种方法可以从字符串中删除空格吗?为什么 .replace 在这种特殊情况下不起作用?

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')
Run Code Online (Sandbox Code Playgroud)

Jos*_*ton 5

replace()返回一个新字符串,它不会修改原始字符串。试试这个:

string = string.replace(" ", "")
Run Code Online (Sandbox Code Playgroud)