sdaau
sdaau

Reputation: 38619

Using regex in python to search for floats, and replace them with reduced float precision in a string?

Apologies if this has been answered already - I tried looking it up, but maybe my search terms (same as my title) were bad.

Let's assume I have a string like this, which I don't have control over:

astr = "A 5.02654824574 (14.710000000000008, -19.989999999999995, -0.8) <-> s[10]: A 5.02654824574 (-29.11999999999999, 52.78, -0.8)"

I would like to process this string, so that floats in it are displayed with arbitrary amount of float precision - say 3 decimals. Since this would work on a level of a string, I wouldn't expect the process to account for correct rounding - simply for removal of decimal point string characters.

I'm aware I could do, as per Python: Extract multiple float numbers from string :

import re
p = re.compile(r'\d+\.\d+')
for i in p.findall(astr): print i

... which prints:

5.02654824574
14.710000000000008
19.989999999999995
0.8
5.02654824574
29.11999999999999
52.78
0.8

.... however, I'm getting lost at which regex captures I need to do in a search and replace, so - say, for n_float_precision_decimals = 4, - I'd get this string as output (with the above string as input):

"A 5.0265 (14.7100, -19.9899, -0.8) <-> s[10]: A 5.0265 (-29.1199, 52.78, -0.8)"

So basically, the regex would be taking into account that if there is a smaller number of decimals present already, it would not truncate decimals at all.

Is this possible to do, in a single re.sub operation, without having to write explicit for loops as above, and manually constructing the output string?

Upvotes: 2

Views: 1237

Answers (1)

sdaau
sdaau

Reputation: 38619

Got it - thanks to Reduce float precision using RegExp in swift ( which popped up in SO suggestions only after I finished typing the entire question (during which time, all I got were irrelevant results for this particular question) :) ):

>>> pat=re.compile(r'(\d+\.\d{2})\d+')
>>> pat.sub(r'\1', astr)
'A 5.02 (14.71, -19.98, -0.8) <-> s[10]: A 5.02 (-29.11, 52.78, -0.8)'

... or:

>>> nfloatprec=4
>>> pat=re.compile(r'(\d+\.\d{'+str(nfloatprec)+'})\d+')
>>> pat.sub(r'\1', astr)
'A 5.0265 (14.7100, -19.9899, -0.8) <-> s[10]: A 5.0265 (-29.1199, 52.78, -0.8)'

Upvotes: 2

Related Questions