I have a function taking float arguments (generally integers or decimals with one significant digit), and I need to output the values in a string with two decimal places (5 -> 5.00, 5.5 -> 5.50, etc). How can I do this in Python?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
f-string formatting:
This is new in Python 3.6 - the string is placed in quotation marks as usual, prepended with
f'...
in the same way you wouldr'...
for a raw string. Then you place whatever you want to put within your string, variables, numbers, inside bracesf'some string text with a {variable} or {number} within that text'
- and Python evaluates as with previous string formatting methods, except that this method is much more readable.You can see in this example we format with decimal places in similar fashion to previous string formatting methods.
NB
a
can be an number, variable, or even an expression egf'{3*my_func(3.14):02f}'
.Going forward, with new code f-strings should be preferred over common %s or str.format() methods as f-strings are much faster.
Since this post might be here for a while, lets also point out python 3 syntax:
You could use the string formatting operator for that:
The result of the operator is a string, so you can store it in a variable, print etc.
String formatting:
Using Python 3 syntax:
Using python string formatting.