PyProgram #1 – Replacing contents of a string using a dictionary of replacements

Came across a nice programming problem, actually intended for an exam on Python. Was in a mood to try solving them using my ‘solpa’ knowledge of Python.

Problem: Given the input string ‘aabbabccdab’, replace the characters as follows: a with l, b with m, c with n, d with o, using dictionaries. The replacement should produce a new string, instead of changing the original string.


Create an input string

inputstr = ‘aabbabccdab’

Create a dictionary of replacement letter pairs

convdict = {‘a’:’l’, ‘b’:’m’, ‘c’:’n’, ‘d’:’o’}

We have the input string, how to read individual letters? Try this

# for x in inputstr: print x

Now we have to read each letter to the string, find the replacement letter from the dict and replace it. Wait! Rather add it to a new string. One way is to initialize an empty list and add letter by letter to it and finally join them as a string.

outputlst = []

So, here is the python code which is going to do the replacement and append it to the list.

for x in inputstr: outputlst.append(convdict[x])

But, now we have only a list of the letters replaced from the string, while we need an output string. So, we have to join the elements of the list.

import string

outputstr = string.join(outputlst, ”)

Hmm, let us check.

print outputstr



Is there a better way than to do this ? Without using list, of course, just add the replacements to a string.

outputstrn = “”

for x in inputstr: outputstrn = outputstrn+convdict[x]

print outputstrn

Always try to do it simple, the way your are confident of getting an answer. Once you are done, have a second look of making the code small and further simple. Hope, I did come up with a decent solution. 🙂

With respect to Sridhar Ratna‘s comment, I tried to make use of string.makestrans(). After a little help from Casanova, I could end up with a little different but a simpler solution. But am not sure how to use a dictionary of replacement letters in this method, will figure it soon 🙂

Module: string

Syntax: maketrans(from, to) –> string

Description: Returns a translation table, a string of 256 bytes long,, suitable for use in strings.translate. The strings from and to must be of the same length.


import string

transtr = string.maketrans(“abcd”,”lmno”)

outputstr = string.translate(“aabbabccddab”,transtr)

print outputstr



One thought on “PyProgram #1 – Replacing contents of a string using a dictionary of replacements

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s