Home > Blockchain >  Python - sub for multiple variables
Python - sub for multiple variables

Time:10-07

What would be elegant/pythonic way to pass multiple string variables through a sub? I need to pass multiple varialbes to sub to replace string chunk that appears in every single one of them.

My working code which I want to avoid:

import re

txt = "aaa"
txt2 = "aaaCCC"

txt = re.sub(r'aaa', 'bbb', txt)
txt2 = re.sub(r'aaa', 'bbb', txt2)

print(txt)
print(txt2)

CodePudding user response:

import re

txt = "aaa"
txt2 = "aaaCCC"

original = [txt, txt2]

subbed = [re.sub(r'aaa', 'bbb', x) for x in original]

print(subbed[0])
print(subbed[1])

CodePudding user response:

You could use a functools.partial to create a mappable function:

mappable = functools.partial(re.sub, 'aaa', 'bbb')

This is roughly equivalent to doing

mappable = lambda t: re.sub('aaa', 'bbb', t)

The main differences are that partial makes a proper function wrapper with a fancy name and other attributes based on the underlying function.

You can map with a map or a comprehension:

txt, txt2 = map(mappable, (txt, txt2))

Unpacking the generator evaluates it. A list comprehension does the same:

result = [mappable(t) for t in (txt, txt2)]
  • Related