我正在尝试删除空格。
我已经尝试了以前的线程中的所有内容,包括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. :(
答案 0 :(得分:4)
您遇到的问题是:
cleanword = wordinput.replace(" ","")
cleanword = wordinput.replace(",","")
cleanword = wordinput.replace(".","")
您没有保存先前替换的结果。
尝试:
cleanword = wordinput.replace(" ", "").replace(",", "").replace(".", "")
答案 1 :(得分:2)
@StephenRauch explains你的问题很好。
但这是实现逻辑的更好方法:
chars = ',. '
wordinput = 'mr owl ate my metal worm '
cleanword = wordinput.translate(dict.fromkeys(map(ord, chars)))
# 'mrowlatemymetalworm'
答案 2 :(得分:1)
您尝试过类似的事情吗?
import re
cleanword = re.sub(r'\W+', '', wordinput.lower())
答案 3 :(得分:1)
wordinput = (input("Input:\n"))
cleanword=''.join([e for e in wordinput.lower() if e not in ", ."])
你可以尝试这种理解
答案 4 :(得分: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!"')
答案 5 :(得分: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. :(')