Question

A list of string replacements in Python

Is there a far shorter way to write the following code?

my_string = my_string.replace('A', '1')
my_string = my_string.replace('B', '2')
my_string = my_string.replace('C', '3')
my_string = my_string.replace('D', '4')
my_string = my_string.replace('E', '5')

Note that I don't need those exact values replaced; I'm simply looking for a way to turn 5+ lines into fewer than 5

 45  81990  45
1 Jan 1970

Solution

 73

Looks like a good opportunity to use a loop:

mapping = { 'A':'1', 'B':'2', 'C':'3', 'D':'4', 'E':'5'}
for k, v in mapping.iteritems():
    my_string = my_string.replace(k, v)

A faster approach if you don't mind the parentheses would be:

mapping = [ ('A', '1'), ('B', '2'), ('C', '3'), ('D', '4'), ('E', '5') ]
for k, v in mapping:
    my_string = my_string.replace(k, v)
2009-04-18

Solution

 50

You can easily use string.maketrans() to create the mapping string to pass to str.translate():

import string
trans = string.maketrans("ABCDE","12345")
my_string = my_string.translate(trans)
2009-04-19