user60684 user60684 - 3 months ago 20
Python Question

Alternative to multiple regexes for replacing known words in Python

In Python 3 I have the string " up2 left5 right4 down2". I wish to convert this to " u2 l5 r4 d2", keeping the numbers. What's the most efficient way of doing this? I imagine there's a better method than 4 regexes.

The only possible words are "up" "down" "left" and "right", the numbers can be anything from 0 to 999. How can I efficiently replace these 4 words with their 1-character abbreviations?

Answer Source
for t in (('up', 'u'), ('down','d'), ('left','l'), ('right', 'r')):
   mystring = mystring.replace(*t)

or, taking advantage of the fact that replacement for a word is always its first letter:

for word in ('up','down','left','right'):
    mystring = mystring.replace(word, word[0])