Search code examples
pythonpython-3.xstringfloating-pointrounding

How can I round a string made of numbers efficiently using Python?


Using Python 3...

I've written code that rounds the values for ArcGIS symbology labels. The label is given as a string like "0.3324 - 0.6631". My reproducible code is...

label = "0.3324 - 0.6631"
label_list = []
label_split = label.split(" - ") 
for num in label_split:
    num = round(float(num), 2) # rounded to 2 decimals
    num = str(num)
    label_list.append(num) 
label = label_list[0]+" - "+label_list[1]

This code works but does anyone have any recommendations/better approaches for rounding numbers inside of strings?


Solution

  • This solution doesn't try to operate on a sequence but on the 2 values.

    A bit more readable to me.

    x, _, y = label.partition(" - ")
    label = f"{float(x):.2f} - {float(y):.2f}"