Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 522
Dan Avatar asked Nov 27 '17 16:11

Dan


People also ask

What is string interpolation 1 point?

In computer programming, string interpolation (or variable interpolation, variable substitution, or variable expansion) is the process of evaluating a string literal containing one or more placeholders, yielding a result in which the placeholders are replaced with their corresponding values.

How do I format a string to two decimal places?

String strDouble = String. format("%. 2f", 1.23456); This will format the floating point number 1.23456 up-to 2 decimal places, because we have used two after decimal point in formatting instruction %.

How do you format to 2 decimal places in Python?

In Python, to print 2 decimal places we will use str. format() with “{:. 2f}” as string and float as a number. Call print and it will print the float with 2 decimal places.

How do you do 2 decimal places in Java?

Just use %. 2f as the format specifier. This will make the Java printf format a double to two decimal places.


2 Answers

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'
like image 159
tobias_k Avatar answered Sep 30 '22 07:09

tobias_k


Yes, you can escape string templating literals with double curly braces:

decimals = 5
template = f'{{some_float:{decimals}.f}}'
// '{some_float:5.f}'
template.format(some_float=some_float)

I don't think you can use formatted string literals for the second substitution, but I think it's a nice solution anyway.

I think you made a mistake in the first code example in your question, the dot is in a wrong place in your formatter. (3.f instead of .3f)

like image 21
fodma1 Avatar answered Sep 30 '22 07:09

fodma1