bqui56
bqui56

Reputation: 2121

Accessing capture groups during substitution

I have a text file containing decimal numbers throughout it and was wanting to round up any that have a decimal >= 0.5, otherwise I want to truncate the decimal, e.g., 23.7897 becomes 24 and 17.2395 becomes 17.

The < 0.5 case is not a problem for re.sub:

re.sub(r'(\d+)\.[0-4]\d*', r'\1', line)

however, for the >= 0.5 case, I was wondering if there was a way to manipulate the \1 capture group during the substitution somehow? Is it stored anywhere so that it can be sent to a function, e.g.:

re.sub(r'(\d+)\.[5-9]\d*', roundUp('\1'), line)

where roundUp() returns a string representing the value \1 + 1.

Surely there is a way to just increment \1 inline during substitution without having loop through the matches from findall, incrementing the integer part, then refinding the pattern with re.sub and subtitute it in?

Upvotes: 1

Views: 125

Answers (1)

Jamey Sharp
Jamey Sharp

Reputation: 8501

You can use an arbitrary callable for the replacement, so does this work for you?

re.sub(r'\d+\.\d*', lambda match: str(int(round(float(match.group(0))))), line)

Upvotes: 2

Related Questions