输入是否为回文

Whether the input is a palidrome or not

所以,我正在写一个代码来检查输入的字符串是否是回文,我写了下面的代码,但是它不能正常工作,例如,如果我输入 "race" 它仍然说 TRUE,虽然它应该说 FALSE,请帮助。 这是代码

string = input("Please enter any word: ")
a = 0
string_length = len(string)
for string_index in range(string_length-1, -1, -1):
    character = string[string_index]
    if string[a] == character:
        a = a + 1
        b = "TRUE"
    else:
        b = "FALSE"
print(b) 

正确代码:

a = 0
string_length = len(string)
for string_index in range(string_length-1, -1, -1):
    character = string[string_index]
    if string[a] == character:
        a = a + 1
        b = "TRUE"
    else:
        b = "FALSE"
        break;  # this line was missing
print(b) 

除了

您可以轻松地将您的输入与其自身进行反向比较 - 列表理解使这变得微不足道:

简单的 1 个单词和区分大小写的测试:

word = "SomemoS"
print(word == word[::-1])  # word[::-1] simply reverses the word and prints True if same

不区分大小写并允许使用标点符号

一个回文从两面都是可读的。根据回文规则,您可能允许忽略大小写,甚至消除空格和 标点符号。

  • 对其应用 lower()
  • 不关心空格和标点符号

word = [c.lower() for c in "No, it can assess an action." if c not in ',. !?']
print(word == word[::-1])  # True as well
string = input("Please enter any word: ")
string_length = len(string)
start_index = 0
count = 0 
end_index = string_length - 1
for string_index in range(int(string_length/2)):
    if string[start_index] == string[end_index]:
        start_index = start_index + 1
        end_index = end_index - 1
        count += 1
    else:
        pass
print("Palendrome") if count == int(string_length/2) else print("Not Palendrome")

说明: 要检查回文字符串,比较第一个和最后一个字符,直到比较到达字符串的中间

for string_index in range(int(string_length/2)):

比较第一个字符和最后一个字符:

if string[start_index] == string[end_index]:

更新 start_index 和 end_index 并计数:

start_index = start_index + 1
end_index = end_index - 1
count += 1

如果count等于字符串长度的一半那么它肯定是回文

print("Palendrome") if count == int(string_length/2) else print("Not Palendrome")