Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 17331

Best way to use re.sub with a different behavior when first called

$
0
0

I'm trying to perform a number of replacements using re.sub(), except I want the first replacement to be different. One straightforward approach would be to run re.sub() twice with count = 1 for the first call, but because re.sub() allows for the repl argument to be a function, we can do this in a single call:

import redef repl(matchobj):    global first_sub    if first_sub:        first_sub = False        print(f"Replacing '{matchobj.group()}' at {matchobj.start()} with ':)'")        return ":)"    else:        print(f"Deleting '{matchobj.group()}' at {matchobj.start()}")        return ""text = "hello123 world456"first_sub = Truetext = re.sub(r"\d+", repl, text)# Output:#   Replacing '123' at 5 with ':)'#   Deleting '456' at 14

Unfortunately, this makes use of global, which isn't great. Is there a better way to do this?


Viewing all articles
Browse latest Browse all 17331

Latest Images

Trending Articles



Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>