Can I make a code in python that ignores special c

2020-04-21 05:55发布

I want to create a code that will return "true" (if I type in a palindrome regardless of case or if there are special characters in it), and "false" otherwise. The code I have so far works for phrases with no special characters such as commas, apostrophes, spaces, etc.

def is_palindrome(my_str):
    my_str= my_str.casefold()
    rev_str= reversed(my_str)

if list(my_str) == list(rev_str):
   print("True")
else:
   print("False")

when I do:

 print (is_palindrome("Rats live on no evil star"))

it returns True because it is a palindrome

when I do:

 print (is_palindrome("Hello World!"))

it returns False because it is not a palindrome

when I do:

 print (is_palindrome("Madam, I'm Adam"))

it returns False. but I want to create a code that considers this a palindrome

4条回答
你好瞎i
2楼-- · 2020-04-21 06:27

If you just want to exclude punctuation and spaces you can use str.translate:

from string import punctuation

d = {k: None for k in punctuation}
d[" "] = None

def is_palindrome(my_str):
    trans = str.maketrans(d)
    my_str = my_str.translate(trans).casefold()
    return my_str == my_str[::-1]
查看更多
Animai°情兽
3楼-- · 2020-04-21 06:34
my_str = my_str.casefold()
my_str = ''.join(e for e in my_str if e.isalpha())

This should recreate my_str with only alphabetical characters, using .isalpha(). Then do the test on that. If you want to keep a record of original string, just stored the recreated version is a temporary string.

查看更多
迷人小祖宗
4楼-- · 2020-04-21 06:39

You need to filter before testing then:

letters = [c.casefold() for c in my_str if c.isalpha()]

would pick out only the letters and lowercase them, after which you can test of those letters form a palindrome:

return letters == letters[::-1]

This works because str.isalpha() returns True only for letters.

Combined into your function:

def is_palindrome(my_str):
    letters = [c.casefold() for c in my_str if c.isalpha()]
    return letters == letters[::-1]

Demo:

>>> def is_palindrome(my_str):
...     letters = [c.casefold() for c in my_str if c.isalpha()]
...     return letters == letters[::-1]
... 
>>> is_palindrome("Rats live on no evil star")
True
>>> is_palindrome("Hello World!")
False
>>> is_palindrome("Madam, I'm Adam")
True
查看更多
聊天终结者
5楼-- · 2020-04-21 06:48

You may get just alphanumeric character in your string;

re.sub(r'[^a-zA-Z0-9]+', '', your_string).lower()

By the way this one works, if you ignores non-ASCII chars.

查看更多
登录 后发表回答