Python 3 string format decimal places

Python v2.7 introduced a new string fomatting method, that is now the default in Python3. I started this string formatting cookbook as a quick reference to help me format numbers and strings. Thanks to other contributors I’ve expanded the examples over time.

Python 3.6 introduced, formatted string literals, often referred to as f-strings as another method to help format strings. Jump to the new F-strings section below.

Number Formatting

The following table shows various ways to format numbers using Python’s str.format[], including examples for both float formatting and integer formatting.

To run examples use: print["FORMAT".format[NUMBER]];

To get the output of the first example, formatting a float to two decimal places, you would run:

print["{:.2f}".format[3.1415926]];

NumberFormatOutputDescription
3.1415926 {:.2f} 3.14 Format float 2 decimal places
3.1415926 {:+.2f} +3.14 Format float 2 decimal places with sign
-1 {:+.2f} -1.00 Format float 2 decimal places with sign
2.71828 {:.0f} 3 Format float with no decimal places
5 {:0>2d} 05 Pad number with zeros [left padding, width 2]
5 {:x

Chủ Đề