原文: https://www.programiz.com/python-programming/examples/palindrome
要理解此示例,您应该了解以下 Python 编程主题:
回文是指向前或向后读取相同的字符串。
例如,"dad"在正向或反向上相同。 另一个例子是'aIbohPhoBiA',其字面意思是对回文的一种烦躁的恐惧症。
# Program to check if a string is palindrome or not
my_str = 'aIbohPhoBiA'
# make it suitable for caseless comparison
my_str = my_str.casefold()
# reverse the string
rev_str = reversed(my_str)
# check if the string is equal to its reverse
if list(my_str) == list(rev_str):
print("The string is a palindrome.")
else:
print("The string is not a palindrome.") 输出
The string is a palindrome.注意:要测试程序,请在程序中更改my_str的值。
在此程序中,我们采用了存储在my_str中的字符串。
使用方法casefold(),我们使其适用于无条件的比较。 基本上,此方法返回字符串的小写版本。
我们使用内置函数reversed()反转字符串。 由于此函数返回反向对象,因此在比较之前,我们使用list()函数将它们转换为列表。