I'd like to show you my own solution. At the first view, it might be complicated, but after defining the "basics", application is really simple
First, I define a mapping as a list of tuples:
our_mapping = [("Northern", "N"),
("Western", "W"),
("Southern", "S"),
("Eastern", "E")]
Now comes the beef: I define a factory function that recursively creates an All-In-One replacement function:
def replacer_factory(mapping):
if len(mapping) < 1:
return lambda x: x
original, replacement = mapping[0]
return lambda x: replacer_factory(mapping[1:])(x.replace(original, replacement))
Now I can create a replacement function with my mapping:
our_replacer = replacer_factory(our_mapping)
And then application is really easy:
>>> in_ = "Northern Western Southern Eastern"
>>> out_ = our_replacer(in_)
>>> print in_
Northern Western Southern Eastern
>>> print out_
N W S E
I really like that we don't need any parameters to call our_replacer, all the mapping-logic has been hidden inside of it. One can now easily define arbitrary replacers and use them.
Here the code as a whole:
our_mapping = [("Northern", "N"),
("Western", "W"),
("Southern", "S"),
("Eastern", "E")]
def replacer_factory(mapping):
if len(mapping) < 1:
return lambda x: x
original, replacement = mapping[0]
return lambda x: replacer_factory(mapping[1:])(x.replace(original, replacement))
our_replacer = replacer_factory(our_mapping)
in_ = "Northern Western Southern Eastern"
out_ = our_replacer(in_)
print in_
print out_
I agree that this can be considered "advanced" - so if you are a newbie and "just want it to work", stick to jabaldonedos answer.