检查 python 中的回文

Check for a palindrome in python

回文

这是我目前编写的代码:

string=input(("Enter a string:"))
for char in string:
    print(char)
if(string==string[::-1]):
      print("The string is a palindrome")
else:
      print("Not a palindrome")

要生成所描述的输出,您似乎需要执行逐字符比较。您尝试的是将字符串与其反向进行直接比较。试试这个:

string=input(("Enter a string:"))
rev_string = string[::-1]
for i in range(len(string)):
    print (string[i], "--", rev_string[i])
    if string[i].lower() != rev_string[i].lower():
        print("Not a palindrome")
        exit(0)
print("The string is a palindrome")

我想指出,检查两个字符是否相同并不简单,如 this answer 中所述。以下代码适用于任何字符:

import unicodedata


def normalize_caseless(text):
    return unicodedata.normalize("NFKD", text.casefold())


def caseless_equal(left, right):
    return normalize_caseless(left) == normalize_caseless(right)


string = input("Enter a string: ")
rev_string = string[::-1]

i = 0
palindrome = True
while palindrome and i < len(string):
    print(f'{string[i]} -- {rev_string[i]}')
    palindrome = caseless_equal(string[i], rev_string[i])
    i += 1

print(f"The string is{' not'*(not palindrome)} a palindrome")