我有用户输入字符串,直到他们完成输入完成。然后我检查每个字符串以查看它是否是回文。如果字符串是回文,那么我将其插入列表中。我有我的回文检查代码工作的字符串像“交换爪子”但它不适用于像“ taco cat ”这样的字符串。我不能包含库来帮助我,所以我不确定如何忽略空格和大小写。这与此处提出的其他问题不同,因为那些谈论忽略空间和案例使用库的人和其他人只是讨论检查没有空格或任何特殊的基本字符串是否是回文。这是我的代码:
plist={}
val=1
print("Enter the strings: ")
inp = raw_input() # Get the input
if(inp==inp[::-1]):
plist[inp] = val
while inp != "Done": # Loop until Done is entered
if(inp==inp[::-1]): # inp==inp[::-1]
plist[inp] = val
inp = raw_input() # Get the input again
print("The palindromes are: ")
print(plist)
答案 0 :(得分:1)
这似乎是关于过滤空白字符,你已经想到的回文。
要过滤掉空格字符,您可以执行以下操作:
>>> "".join([c for c in "taco cat" if c != " "])
'tacocat'
对于其他空白字符,您可以更改if过滤器:
... c not in [" ", "\t", "\n", ...]
答案 1 :(得分:0)
在这里,您可以找到答案:
(此程序在Python 3上运行 - 可能某些功能在Python 2或更低版本中有所不同)
# Reverse of a string
def reverse(input_string: str):
return input_string[::-1]
# Main function
def is_palindrome(input_string: str):
# type: () -> bool
reverse_string = reverse(input_string)
return reverse_string == input_string
# Now your program
palindrome_words = []
is_program_finished = False
do:
input_text = input("Put your palindrome here or type \"Done\" for finish: ")
if input_text != "Done":
if is_palindrome(input_text):
palindrome_words.append(input_text)
else:
is_program_finished = True
while not is_program_finished
# I recommend you to use "pprint" for displaying list
from pprint import pprint
pprint(palindrome_words)
# Else:
print(palindrome_words)
希望它有所帮助^^