4

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)
4
  • 5
    Looks like you may need a loop Commented Oct 7, 2021 at 0:58
  • Or maybe list comprehension? Commented Oct 7, 2021 at 1:01
  • 1
    What do you expect it to look like, approximately? Commented Oct 7, 2021 at 1:05
  • 1
    @marcin2x4 That is a loop :) Commented Oct 7, 2021 at 1:12

2 Answers 2

1
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])
Sign up to request clarification or add additional context in comments.

Comments

1

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)]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.