Passing info to function used in re.sub

Peter J. Holzer hjp-python at hjp.at
Mon Sep 4 15:00:02 EDT 2023


On 2023-09-03 18:10:29 +0200, Jan Erik Moström via Python-list wrote:
> I want to replace some text using a regex-pattern, but before creating
> replacement text I need to some file checking/copying etc. My code
> right now look something like this:
> 
> def fix_stuff(m):
> 	# Do various things that involves for info
> 	# that what's available in m
> 	replacement_text = m.group(1) + global_var1 + global_var2
> 	return replacement_text
> 
> and the call comes here
> 
> global_var1 = "bla bla"
> global_var2 = "pff"
> 
> new_text = re.sub(im_pattern,fix_stuff,md_text)
> 
> 
> The "problem" is that I've currently written some code that works but
> it uses global variables ... and I don't like global variables. I
> assume there is a better way to write this, but how?

If you use fix_stuff only inside one other function, you could make it
local to that function so that it will capture the local variables of
the outer function:

import re

def demo():

    local_var1 = "bla bla"
    local_var2 = "pff"

    def fix_stuff(m):
        # Do various things that involves for info
        # that what's available in m
        replacement_text = m.group(1) + local_var1 + local_var2
        return replacement_text

    for md_text in ( "aardvark", "barbapapa", "ba ba ba ba barbara ann"):
        new_text = re.sub(r"(a+).*?(b+)", fix_stuff, md_text)
        print(md_text, new_text)

demo()

        hp

-- 
   _  | Peter J. Holzer    | Story must make more sense than reality.
|_|_) |                    |
| |   | hjp at hjp.at         |    -- Charles Stross, "Creative writing
__/   | http://www.hjp.at/ |       challenge!"
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 833 bytes
Desc: not available
URL: <https://mail.python.org/pipermail/python-list/attachments/20230904/1469b5ec/attachment.sig>


More information about the Python-list mailing list