欢迎访问宙启技术站
智能推送

Python函数:检测是否为回文字符串

发布时间:2023-11-11 23:36:41

回文字符串是指正向和逆向读取时都相同的字符串。Python中可以使用以下函数来检测一个字符串是否为回文字符串:

def is_palindrome(s):
    # 去除字符串中的空格和标点符号
    s = ''.join(e for e in s if e.isalnum())
    
    # 将字符串转换为小写
    s = s.lower()
    
    # 对称比较字符串的首尾字符
    left, right = 0, len(s) - 1
    while left < right:
        if s[left] != s[right]:
            return False
        left += 1
        right -= 1
        
    return True

在这个函数中,我们首先使用.isalnum()方法去除字符串中的空格和标点符号,然后将字符串转换为小写。接下来,我们使用两个指针leftright来比较字符串的首尾字符。当两个指针指向的字符不相同时,函数返回False,表示字符串不是回文字符串。如果列表中的所有字符都比较完毕,那么函数返回True,表示字符串是回文字符串。

以下是一些运行该函数的示例:

print(is_palindrome("racecar"))  # True
print(is_palindrome("A man, a plan, a canal, Panama"))  # True
print(is_palindrome("hello"))  # False

在上面的示例中, 个示例字符串racecar是回文字符串,因此函数返回True。第二个示例字符串A man, a plan, a canal, Panama经过处理后为amanaplanacanalpanama,也是回文字符串,函数同样返回True。而第三个示例字符串hello不是回文字符串,因此函数返回False