Reputation: 17
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?
Upvotes: 1
Views: 10086
Reputation: 1
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
Upvotes: 0
Reputation: 14
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]
Upvotes: 0
Reputation: 54514
def palindrome(n):
x = ''.join([x.lower() for x in n if x.isalpha()])
return x == x[::-1]
Upvotes: 2
Reputation: 113915
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
Upvotes: 3