varInt = 12
print(
"Integer : " +
"{:07.3f}".format(varInt)
)
Outputs:
Integer : 012.000
The 7 is total field width and includes the decimal point.
Answer from Andy on Stack Overflowstring - How to format a floating number to fixed width in Python - Stack Overflow
python - Quickly formatting numbers in print() calls with tuples mixing strings and numbers - Stack Overflow
Math with Significant Figures
Do you normally use string.format() or percentage (%) to format your Python strings?
Firstly, you can write e. g. {0:.2f} to specify a float with 2 decimals, see e. g. https://www.digitalocean.com/community/tutorials/how-to-use-string-formatters-in-python-3
Secondly, the best formatting method is f-strings, see e. g. https://www.blog.pythonlibrary.org/2018/03/13/python-3-an-intro-to-f-strings/
More on reddit.comVideos
varInt = 12
print(
"Integer : " +
"{:07.3f}".format(varInt)
)
Outputs:
Integer : 012.000
The 7 is total field width and includes the decimal point.
Not only can you specify the minimum length and decimal points like this:
"{:07.3f}".format(12)
You can even supply them as parameters like this:
"{:0{}.{}f}".format(12, 7, 3)
numbers = [23.23, 0.1233, 1.0, 4.223, 9887.2]
for x in numbers:
print("{:10.4f}".format(x))
prints
23.2300
0.1233
1.0000
4.2230
9887.2000
The format specifier inside the curly braces follows the Python format string syntax. Specifically, in this case, it consists of the following parts:
- The empty string before the colon means "take the next provided argument to
format()" โ in this case thexas the only argument. - The
10.4fpart after the colon is the format specification. - The
fdenotes fixed-point notation. - The
10is the total width of the field being printed, lefted-padded by spaces. - The
4is the number of digits after the decimal point.
It has been a few years since this was answered, but as of Python 3.6 (PEP498) you could use the new f-strings:
numbers = [23.23, 0.123334987, 1, 4.223, 9887.2]
for number in numbers:
print(f'{number:9.4f}')
Prints:
23.2300
0.1233
1.0000
4.2230
9887.2000