Find mirror characters in a string in Python

In this tutorial, you will see how to find mirror characters of a string using python.

First of all, you need to know what are mirror characters. Mirror characters mean ‘a’ corresponds to ‘z’, ‘A’ corresponds to ‘Z’, ‘b’ corresponds to ‘y’, ‘B’ corresponds to ‘Y’ and likewise.

All the small English alphabets and their mirror characters could be represented as abcdefghijklm || nopqrstuvwxy

All the small English alphabets and their mirror characters could be represented as ABCDEFGHIJKLM|| NOPQRSTUVWXYZ

Given an index ‘n’, we need to mirror the characters from Nth position up to the length of the string in alphabetical order.

Python program to find mirror characters in a string

Now, to achieve this we take two strings (or character array) where we store the English lowercase letters and uppercase letters respectively. We will take the difference between theĀ  ASCII value of the character of the original string and the ASCII value of the first letter of the English alphabet(‘a’ for lowercase letters and ‘A’ for uppercase letters) as an index to obtain its mirror character.

#function which takes the string to be reversed
#the position from where reversing begins 
#and finally returns the modified string
def compute_reverse(s,n):
    #string containing reverse alphabets
    reverse_small="zyxwvutsrqponmlkjihgfedcba"
    reverse_capital="ZYXWVUTSRQPONMLKJIHGFEDCBA"   
    length=len(s)
    st=" "
    #forms the modified string with no change     
    #from starting upto the positon from where reversing starts 
    for i in range(0, n): 
        st = st + s[i]; 
    #forming mirror characters of the given string 
    #starting from the given position till the end of the string
    #by taking index in the reverse as the difference between
    #the  ASCII of the character in the origional string
    #and the ASCII value of character 'a'
    for i in range(n,length):
        if ord(s[i])>=65 and ord(s[i])<=90:
             st = (st + reverse_capital[ord(s[i]) - ord('A')])
        elif  ord(s[i])>=97 and ord(s[i])<=122:
            st= (st+ reverse_small[ord(s[i])-ord('a')])
            
        
    return st;



s="alphaBet"                    #given string
n=3                             #given position
answer=compute_reverse(s,n-1)
print(answer)

Output :

alkszYvg

In the above Python program, you can follow the comment lines to know what we did in each and every step.

Leave a Reply

Your email address will not be published. Required fields are marked *