Replacements with items from a list with re.sub?

What is the best way to do replacements with re.sub given a list? For instance:

 import re some_text = ' xxxxxxx@yyyyyyyyy @ zzzzzzzzz@ ' substitutions = ['ONE', 'TWO', 'THREE'] x = re.sub('@', lambda i: i[0] substitutions.pop(0), some_text) # this doesn't actually work 

Desired Result:

 some_text = 'xxxxxxxONEyyyyyyyyyTWOzzzzzzzzzTHREE' 
+4
source share
3 answers

You just have a syntax error in your lambda:

 >>> substitutions = ['ONE', 'TWO', 'THREE'] >>> re.sub('@', lambda _: substitutions.pop(0), some_text) 'xxxxxxxONEyyyyyyyyyTWOzzzzzzzzzTHREE' 

If you do not want to modify the list, you can wrap it iterable.

 >>> substitutions = ['ONE', 'TWO', 'THREE'] >>> subs = iter(substitutions) >>> re.sub('@', lambda _: next(subs), some_text) 'xxxxxxxONEyyyyyyyyyTWOzzzzzzzzzTHREE' 
+5
source

One way (probably the best, I don't know Python) is to compile a regular expression, and then use sub instead:

 import re some_text = ' xxxxxxx@yyyyyyyyy @ zzzzzzzzz@ ' substitutions = ['ONE', 'TWO', 'THREE'] pattern = re.compile('@') x = pattern.sub(lambda i: substitutions.pop(0), some_text) 

Here is a demo.

+1
source

The code is almost correct, it needs a little syntax error correction:

 import re some_text = ' xxxxxxx@yyyyyyyyy @ zzzzzzzzz@ ' substitutions = ['ONE', 'TWO', 'THREE'] x = re.sub('@', lambda i: substitutions.pop(0), some_text) # the error was in the lambda function 
+1
source

Source: https://habr.com/ru/post/1398483/


All Articles