How can I check if a word or sentence is a palindrome?

I have to check if the word or sentence is a palindrome using code, and I was able to check the words, but I am having trouble checking sentences like a palindrome. Here is my code, this is short, but I'm not sure how else to add it to check palindromes suggestion. I'm kind of a python beginner, and I've already looked at other people's code, and they are too complicated for me to really understand . Here is what I wrote:

def is_palindrome(s):
  if s[::1] == s[::-1]:
    return True
  else:
    return False

Here's an example of a sentence palindrome: "Red roses don't take risks, sir, in the order of nurses." (If you ignore spaces and special characters)

+4
source share
5 answers
import string

def is_palindrome(s):
    whitelist = set(string.ascii_lowercase)
    s = s.lower()
    s = ''.join([char for char in s if char in whitelist])
    return s == s[::-1]
+8

, :

  • new_s new_s[::-1] .

:

import string

valid = set(string.ascii_letters)
result_s = ''.join([ch for ch in original_s if ch in valid])

:

result_s.casefold() == result_s.casefold()[::-1]

:

import string

s = "Red roses run no risk, sir, on nurses order"
s2 = "abcba"
s_fail = "blah"

def is_palindrome(s):
    valid = set(string.ascii_letters)
    result_s = ''.join([ch for ch in s if ch in valid])
    cf_s = result_s.casefold()
    return cf_s == cf_s[::-1]

assert(is_palindrome(s))
assert(is_palindrome(s2))
assert(is_palindrome(s_fail))  # throws AssertionError
+3

, :

letters = ''.join(c for c in words if c in string.letters)
is_palindrome(letters)

lower :

def is_palindrome(s):
    s = ''.join(c for c in s if c in string.letters)
    s = s.lower()
    return s == s[::-1]
+2

, :

  • . :

    >>> my_sentence = 'Hello World Hello'
    >>> words = my_sentence.split()
    >>> words == words[::-1]
    True
    
  • . :

    >>> my_sentence = 'Hello World Hello'
    >>> my_sentence == my_sentence[::-1]
    False 
    

, , - 2, , , . . , str.replace(), , str.lower(). :

>>> my_sentence = 'Red Roses run no risk, sir, on nurses order'
>>> my_sentence = my_sentence.replace(' ', '').replace(',', '').lower()
>>> my_sentence == my_sentence[::-1]
True
0
source

If, at the suggestion of the palindrome, you ignore spaces, you can do this as follows:

is_palindrome(sentence.replace(' ', ''))
0
source

Source: https://habr.com/ru/post/1660856/


All Articles