Having a str i would like to round the floats/numbers inside a given string:
i.e.:
'fooo <= 0.5615000128746033 and bar <= 567.511'
given for example the restriction of 2 decimals:
'fooo <= 0.56 and bar <= 567.51'
which will be the optimal way to do it?
I imagine a some lines of code to accomplish it, any suggestion on a more or less one liner way?
As this is about performance and oneliner, the procedure I have so far is:
# find floats from string
import re
re.findall("\d+\.\d+", 'fooo <= 0.5615000128746033 and bar <= 567.511')
# find the other non-float elements and concatenate with the rounded float strings
>Solution :
You can simply use re.sub as exactly as what follows:
import re
def rounder(flt):
return str(round(float(flt.group())*100)/100)
example = 'fooo <= 0.5615000128746033 and bar <= 567.511'
re.sub('\d+\.\d+', rounder, example)
Output
fooo <= 0.56 and bar <= 567.51
Explanation
I have defined a function that gets the matched string and transforms it into float and round it to two decimals. This function can be used in re.sub as an argument.