1

palindrome

Here is the code i have written so far:

string=input(("Enter a string:"))
for char in string:
    print(char)
if(string==string[::-1]):
      print("The string is a palindrome")
else:
      print("Not a palindrome")

2 Answers2

1

To produce the described output, it looks like you'd need to perform character-wise comparison. What you've attempted is a straight-forward comparison of a string with it's reverse. Try this:

string=input(("Enter a string:"))
rev_string = string[::-1]
for i in range(len(string)):
    print (string[i], "--", rev_string[i])
    if string[i].lower() != rev_string[i].lower():
        print("Not a palindrome")
        exit(0)
print("The string is a palindrome")
Prateek Dewan
  • 1,587
  • 3
  • 16
  • 29
0

I would like to point out that checking if two characters are the same is not trivial, as discussed in this answer. The following code should work for any character:

import unicodedata


def normalize_caseless(text):
    return unicodedata.normalize("NFKD", text.casefold())


def caseless_equal(left, right):
    return normalize_caseless(left) == normalize_caseless(right)


string = input("Enter a string: ")
rev_string = string[::-1]

i = 0
palindrome = True
while palindrome and i < len(string):
    print(f'{string[i]} -- {rev_string[i]}')
    palindrome = caseless_equal(string[i], rev_string[i])
    i += 1

print(f"The string is{' not'*(not palindrome)} a palindrome")
mapf
  • 1,906
  • 1
  • 14
  • 40