1

So, basically I want to check if a string is palindrome or not

I know I can simply use

def palindrome(n): return n == n[::-1] 

It works fine, but if I want a string, for example "A cat, one crab, lol: barcenotaca." to be true as well, what can I do?

4 Answers 4

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

Checking for char.isalpha() lets you ignore everything that's not a letter (when combined with the n = n.lower(), it basically checks for only lowercase letters) That way, you ignore all the punctuation and whitespace

Sign up to request clarification or add additional context in comments.

2 Comments

what if I want to use stack and a queue to test the parameter string?
@user3672933: what have you tried, and why doesn't it work? I've provided a very pythonic answer, so if you're looking for something different, please show us how/why
2
def palindrome(n): x = ''.join([x.lower() for x in n if x.isalpha()]) return x == x[::-1] 

Comments

0

try checking if every letter in the given string is in the alphabet first, goes something like this

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] 

Comments

0
def palindrome(): stringOne = alphaCheck("give me a lovely palindrome") stringTwo = stringOne[::-1] for i in stringOne: print(i) for j in stringTwo: print(j) if stringOne == stringTwo: return True else: return False def alphaCheck(prompt): stringOne = input(prompt) stringOne = stringOne.replace(" ", "") stringOne = stringOne.lower() while not stringOne.isalpha(): stringOne = input(prompt) return stringOne print(palindrome()) 

this method allows you to input your own palindrome and also checks to ensure that it only contains alphabetic characters. if you want to change that to only digits change while not stringOne.isalpha( ) to is

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.