删除Python中的空格不起作用

问题描述 投票:1回答:6

我想删除空格。我尝试过以前的线程,包括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. :(
python palindrome spaces removing-whitespace
6个回答
1
投票

你尝试过这样的事情:

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

4
投票

你遇到的问题是:

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

您没有保存先前替换的结果。

尝试:

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

2
投票

@StephenRauch explains你的问题很好。

但这是实现逻辑的更好方法:

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

# 'mrowlatemymetalworm'

1
投票
wordinput = (input("Input:\n"))
cleanword=''.join([e for e in wordinput.lower() if e not in ", ."])

你可以尝试这种理解


1
投票

也许你应该尝试这个:

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!"')

1
投票

首次替换后,在后续替换时,您需要使用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. :(')
© www.soinside.com 2019 - 2024. All rights reserved.