我想删除空格。我尝试过以前的线程,包括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. :(
你尝试过这样的事情:
import re
cleanword = re.sub(r'\W+', '', wordinput.lower())
你遇到的问题是:
cleanword = wordinput.replace(" ","")
cleanword = wordinput.replace(",","")
cleanword = wordinput.replace(".","")
您没有保存先前替换的结果。
尝试:
cleanword = wordinput.replace(" ", "").replace(",", "").replace(".", "")
@StephenRauch explains你的问题很好。
但这是实现逻辑的更好方法:
chars = ',. '
wordinput = 'mr owl ate my metal worm '
cleanword = wordinput.translate(dict.fromkeys(map(ord, chars)))
# 'mrowlatemymetalworm'
wordinput = (input("Input:\n"))
cleanword=''.join([e for e in wordinput.lower() if e not in ", ."])
你可以尝试这种理解
也许你应该尝试这个:
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. :(')