In: Computer Science
Answer question in Python, show all code
2) Recall the palindrome problem. Write a new program that prompts the user for a string and checks to see if that string is a palindrome. For this updated program, input strings may have punctuation marks, spaces, and capitalizations, but these are ignored in the palindrome check. Here are some sample interactions.
Please enter a string to check: A man, a plan, a canal: Panama!
The string "A man, a plan, a canal: Panama!" is a palindrome.
Please enter a string to check: No ‘x’ in Nixon
The string "No ‘x’ in Nixon" is a palindrome.
Please enter a string to check: hello students
The string "hello students" is not a palindrome.
Hint: Note that you already know how to check if a string is a palindrome, as long as that string doesn’t include punctuation marks, spaces and both upper and lower case characters. Therefore, your job here is to figure out how to get the input string transformed into a string that does not include these things, and then do the same check you did before
Code:-
def is_palindome(new_string): #palindrome checker
for i in range(len(new_string)):
if new_string[i]!=new_string[len(new_string)-i-1]:
return False
return True
string=input("please enter string to check: ") #taking input from
user
new_string ="" #take new_string
for i in string: #for each character in string
if i.isalpha(): #if i is character
new_string+=i.lower() #append it's lower case character in
new_string
#use can use new_string == new_string[::-1] to check for
palindrome
if (is_palindome(new_string)): #calling function
print("The String "+string+" is a palindrome")
else:
print("The String "+string+" is not a palindrome")
Screenshot:-
Output:-