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

后端 未结 4 1583
余生分开走
余生分开走 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

    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]
    

提交回复
热议问题