Signup/Sign In

Python program to find mirror characters in a string

First, we will learn what are mirror characters in a string. Two characters that are in the same alphabetical position, one from the front and the other from the back are mirror characters. The mirror character of 'a' is 'z', of 'b' is 'y'... and so on.

For a given string a number N, we have to mirror the characters from the Nth position to the end of the string. We will be using a Python dictionary to solve this problem.

Look at the input-output format to understand better.

Input: Studytonight k=6

Output: Studyglmrtsg

Input: Codingfun k=4

Output: Codrmtufm

To execute this task in Python, we will use the concept of a dictionary. We will create a dictionary of characters in alphabetical order and map it with characters in reverse order. Then, we will traverse the characters from the position k of the string and change them into their mirror values using a dictionary.


Follow the algorithm to understand the approach better.

Step 1- Define a function that will mirror the characters present after the kth position

Step 2- Declare variables with correct alphabetical order and reverse order

Step 3- Create a dictionary

Step 4- Slice the string at k into two parts

Step 5- Traverse the characters in the second part of the string and mirror each character

Step 6- Join the first string and the mirrored string

Step 7- Print after string joining as a result

Step 8- Declare a string and value of k

Step 9- Pass the string and k in the function

Python Program

Look at the program to understand the implementation of the above-mentioned approach. With the help of the dict() and zip() method we have created a dictionary where characters in alphabetical order are the key and the character in reverse order will be the value.

def MirrorChar(string,k):
    # create dictionary
    order = 'abcdefghijklmnopqrstuvwxyz'
    reverse = 'zyxwvutsrqponmlkjihgfedcba'
    dictChars = dict(zip(order,reverse))
    # divide string at k    
    pre = string[0:k-1]
    suffix = string[k-1:]
    mirror = ''
    # change suffix into mirror char
    for i in range( len(suffix)):
         mirror = mirror + dictChars[suffix[i]]
    # join prefix and mirrored part
    print (pre+mirror)
st = 'python'
k = 4
print("Mirrored value: ",MirrorChar(st,k))

Mirrored value: pytslm


In this tutorial, we have seen what are mirror characters and for a given string how to mirror the characters which are present after the given position k. We have used a dictionary to map the mirror characters and using it, we have converted the characters in the string into their mirror characters.