Can I make a code in python that ignores special characters such as commas, spaces, exclamation points, etc?

后端 未结 4 1585
余生分开走
余生分开走 2021-01-23 11:39

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 ha

4条回答
  •  我在风中等你
    2021-01-23 12:16

    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
    

提交回复
热议问题