回文是一个正读或反读都相同的字符串。
例如,"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() 函数将其转换为列表。