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
.
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.
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 %.
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.
Just use %. 2f as the format specifier. This will make the Java printf format a double to two decimal places.
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'
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
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With