删除 Python 中的空格无效

Removing Spaces in Python not working

我正在尝试删除空格。 我已经尝试了以前线程中的所有内容,包括 re.sub

代码:

wordinput = (input("Input:\n"))
wordinput = wordinput.lower()
cleanword = wordinput.replace(" ","")
cleanword = wordinput.replace(",","")
cleanword = wordinput.replace(".","")
revword = cleanword [::-1]
print(cleanword)
print(revword)
print("Output:")
if (cleanword == revword):
    print('"The word ' + wordinput + ' is a palindrome!"')
else:
    print('"Unfortunately the word ' + wordinput + ' is not a palindrome. :(')

输出:

Input:
mr owl ate my metal worm 
mr owl ate my metal worm
mrow latem ym eta lwo rm
Output:
"Unfortunately the word mr owl ate my metal worm is not a palindrome. :(

您遇到的问题在这里:

cleanword = wordinput.replace(" ","")
cleanword = wordinput.replace(",","")
cleanword = wordinput.replace(".","")

您没有保存上次替换的结果。

尝试:

cleanword = wordinput.replace(" ", "").replace(",", "").replace(".", "")

你有没有尝试过类似的东西:

import re
cleanword = re.sub(r'\W+', '', wordinput.lower())
wordinput = (input("Input:\n"))
cleanword=''.join([e for e in wordinput.lower() if e not in ", ."])

你可以试试这个理解

你的问题很好

但这里有一个更好的方法来实现您的逻辑:

chars = ',. '
wordinput = 'mr owl ate my metal worm '
cleanword = wordinput.translate(dict.fromkeys(map(ord, chars)))

# 'mrowlatemymetalworm'

也许你应该试试这个:

wordinput = raw_input("Input:\n")

cleanword =''.join([x for x in wordinput.lower() if x not in (',','.',' ')])

if cleanword[:] == cleanword[::-1]:

    print ('"The word ' + wordinput + ' is a palindrome!"')

else:
    print ('"The word ' + wordinput + ' is not a palindrome!"')

第一次替换后,在后续的替换中,您需要使用cleanword,这是更新后的字符串,而不是wordinput。您可以尝试以下操作:

wordinput = (input("Input:\n"))
wordinput = wordinput.lower()
cleanword = wordinput.replace(" ","")

# updating 'cleanword' and saving it 
cleanword = cleanword.replace(",","")
cleanword = cleanword.replace(".","")

revword = cleanword [::-1]
print(cleanword)
print(revword)
print("Output:")

if (cleanword == revword):
    print('"The word ' + wordinput + ' is a palindrome!"')
else:
    print('"Unfortunately the word ' + wordinput + ' is not a palindrome. :(')