Search code examples
pythonpython-3.xstring-formattingstring-interpolationf-string

Choose the number of decimal points in string interpolation


Is there a way to use a variable to decide the number of decimal points in literal string interpolation?

for example if I have something like

f'{some_float:.3f}'

is there a way to replace the 3 with a variable?

The end goal is to add data labels to a bar chart:

def autolabel_bar(rects, ax, decimals=3):
    """
    Attach a text label above each bar displaying its height
    """
    for rect in rects:
        height = rect.get_height()
        ax.text(rect.get_x() + rect.get_width()/2.,
                height + 0.035,
                f'{round(height,decimals):.3f}',
                ha='center',
                va='center')

But I can't think of an easy way to replace the 3 in the string interpolation with the variable decimal.


Solution

  • Format specifiers can be nested. In Python 3.5, this would look e.g. like this:

    "{:.{}f}".format(some_float, decimals)
    

    But it turns out the same also works with Python 3.6 f"..." format strings.

    >>> some_float = math.pi
    >>> decimals = 3
    >>> f"{some_float:.{decimals}f}"
    '3.142'
    

    Also works in combination with round:

    >>> decimals = 5
    >>> f"{round(math.pi, decimals):.{decimals}f}"
    '3.14159'