2016-07-15 4 views
0

何らかの理由でstring.replace( ""、 "")が機能しません。 文字列から空白を削除する別の方法はありますか? この特定の状況で.replaceが動作しないのはなぜですか?pythonで空白を削除しようとしています.replace not working

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') 
+1

文字列は変更できません。 'str.replace()'は* new *文字列オブジェクトを生成しますが、戻り値は無視しています。 –

+0

注記として、スライス表記を使用すると、これをより簡単にすることができます。このような何かは、あなたが回文= 'string == string [:: - 1]: ' – Keatinge

答えて

2

replace()は、新しい文字列を返します。元の文字列は変更されません。代わりにこれを試してください:

string = string.replace(" ", "") 
関連する問題