用于检查字符串是否为回文字符串的 Python 程序

2022-05-03 00:00:00 字符串 用于 回文

要理解此示例,您应该了解以下Python 编程主题:
Python if...else 语句
Python 字符串
字符串方法
回文是向前或向后读取都相同的字符串。

例如,"dad"正向或反向是相同的。另一个例子是“aibohphobia”也是回文字符串。

源代码

# python检测是字符串是否为回文字符串

my_str = 'aIbohPhoBiA'

# 将字符串转为小写
my_str = my_str.casefold()

# 反转字符串
rev_str = reversed(my_str)

# 检测字符串和反转后的字符串是否相同
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()函数将它们转换为列表,然后再进行比较。

相关文章