Search code examples
pythonpython-3.xstringtextpalindrome

Checking whether two strings are a palindrome - ignoring and using case writing?


What follows is a simple script. Basically, I'm experimenting with strings, and I want to check whether a string is a palindrome (ignoring lower upper case), and if it is reverse it with the same writing of the original string (upper- and lowercase):

input = "Repaper"
reverse = reversed(input)

if input == reverse:
    print(reverse)

I don't get any error warning - it's just no input?


Solution

  • First off, using input as a variable is bad practice as it's already a built-in function (see: https://docs.python.org/3/library/functions.html). Sure, it doesn't hurt your code, but it also doesn't benefit you in any way! Why not call the string e.g. input_string or in_str?


    As far as I understood you, you want to compare two strings - ignoring lower- and uppercase writing:
    in_str = 'Anna'
    
    #Ignoring lower-/uppercase
    in_str = in_str.casefold()
    
    #Reversing the string
    rev_str = reversed(in_str)
    

    Now it's important to know that the built-in function reversed(), which we've been using for now, returns a reverse iterator, so we shall (one example) compare via list():

    #Comparing the string and check whether it's a palindrome
    if list(in_str) == list(rev_str):
        #Outputting the reversed string; for example via slicing
        print(in_str[::-1])
    

    -> So for the example input Anna, the output would be annA which should be exactly what you wanted.