Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/318.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/linux/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 检查字符串是否为回文,忽略空格和特殊字符_Python_Palindrome - Fatal编程技术网

Python 检查字符串是否为回文,忽略空格和特殊字符

Python 检查字符串是否为回文,忽略空格和特殊字符,python,palindrome,Python,Palindrome,所以,基本上我想检查一个字符串是否是回文的 我知道我可以简单地使用 def palindrome(n): return n == n[::-1] 它工作得很好,但如果我想要一根线,例如“一只猫,一只螃蟹,哈哈:barcenotaca。” 说实话,我能做什么 def palindrome(n): n = n.lower() n = ''.join(char for char in n if char.isalpha()) return n==n[::-1] 检查

所以,基本上我想检查一个字符串是否是回文的

我知道我可以简单地使用

def palindrome(n):
    return n == n[::-1]
它工作得很好,但如果我想要一根线,例如“一只猫,一只螃蟹,哈哈:barcenotaca。” 说实话,我能做什么

def palindrome(n):
    n = n.lower()
    n = ''.join(char for char in n if char.isalpha())
    return n==n[::-1]
检查
char.isalpha()
可以忽略所有非字母的内容(当与
n=n.lower()
组合使用时,它基本上只检查小写字母),这样就可以忽略所有标点符号和空格

def palindrome(n):
    x = ''.join([x.lower() for x in n if x.isalpha()])
    return x == x[::-1]

检查
char.isalpha(),是这样的

def palindrome(n):
    x = ''.join([x.lower() for x in n if x.isalpha()])
    return x == x[::-1]
import string
def palindrome(str):
    alphabet=string.ascii_lowercase
    temp=""
    for c in str.lower():
        if c in alphabet:
            temp+=c
    return temp==temp[::-1]

首先检查给定字符串中的每个字母是否都在字母表中,如下图所示

import string
def palindrome(str):
    alphabet=string.ascii_lowercase
    temp=""
    for c in str.lower():
        if c in alphabet:
            temp+=c
    return temp==temp[::-1]
此方法允许您输入自己的回文,并进行检查以确保它只包含字母字符。如果要将其更改为仅数字更改,而不是stringOne.isalpha()更改为


此方法允许您输入自己的回文,并进行检查以确保它只包含字母字符。如果要将其更改为仅数字更改而不更改stringOne.isalpha()为is

如果要使用堆栈和队列来测试参数字符串,该怎么办?@user3672933:您尝试了什么,为什么不起作用?我提供了一个非常类似python的答案,因此,如果您正在寻找不同的东西,请向我们展示如何/为什么我想使用堆栈和队列来测试参数字符串?@user3672933:您尝试了什么,为什么不起作用?我提供了一个非常类似于蟒蛇的答案,所以如果你在寻找不同的东西,请告诉我们如何/为什么