在Python中去除空格不起作用

2024-04-27 09:15:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试删除空格。 我已经尝试了以前的所有线程,包括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. :(

Tags: inputismyowlreplacewordmrprint
3条回答

@StephenRauch explains你的问题解决得很好。你知道吗

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

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

# 'mrowlatemymetalworm'

您遇到的问题是:

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

您没有保存上一次替换的结果。你知道吗

尝试:

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

你有没有试过这样的方法:

import re
cleanword = re.sub(r'\W+', '', wordinput.lower())

相关问题 更多 >