Sujet : Re: Passing info to function used in re.sub
De : ram (at) *nospam* zedat.fu-berlin.de (Stefan Ram)
Groupes : comp.lang.pythonDate : 03. Sep 2023, 17:53:02
Autres entêtes
Organisation : Stefan Ram
Message-ID : <advice-20230903173607@ram.dialup.fu-berlin.de>
References : 1
=?utf-8?q?Jan_Erik_Mostr=C3=B6m?= <
lists@mostrom.pp.se> writes:
def fix_stuff(m):
# that what's available in m
replacement_text = m.group(1) + global_var1 + global_var2
return replacement_text
...
new_text = re.sub(im_pattern,fix_stuff,md_text)
You can use a closure:
import re
def make_replace( was_global_1, was_global_2 ):
def replace( matcher ):
return matcher.group( 1 )+ was_global_1 + was_global_2
return replace
replace = make_replace( "a", "b" )
print( re.sub( r'(.)', replace, 'x' ))
. Note how I wrote code one can actually execute.
You could have done this too!
Or, partial application:
import functools
import re
def replace( was_global_1, was_global_2, matcher ):
return matcher.group( 1 )+ was_global_1 + was_global_2
print( re.sub( r'(.)', functools.partial( replace, 'a', 'b' ), 'x' ))
.