Search code examples
pythonregexenumeration

Python - Replace regular expression match with a matching pair value


Let's say I have a list of aliases tied to 5 digit codes available at runtime:

aliasPairs = [(12345,'bob'),(23456,'jon'),(34567,'jack'),(45678,'jill'),(89012,'steph')]

I want to find a terse way to express: replace the id in the line with the matching alias, e.g. :

line = "hey there 12345!"
line = re.sub('\d{5}', value in the aliasPairs which matches the ID, line)
print line

Should output:

hey there bob!

How do Python pros write enumerative expressions in a terse manner?

Thanks and cheers!


Solution

  • Consider using a dictionary when you have a one-to-one mapping of two categories of data, such as five digit codes and aliases. Then it's easy to access any particular alias, given its code:

    import re
    
    aliases = {
        "12345":"bob",
        "23456":"jon",
        "34567":"jack",
        "45678":"jill",
        "89012":"steph"
    }
    
    line = "hey there 12345!"
    line = re.sub('\d{5}', lambda v: aliases[v.group()], line)
    print(line)
    

    Result:

    hey there bob!