How to Format Numbers to Fixed Width in Python
Formatting numbers to a fixed width is a common requirement for creating well-aligned text output, reports, and tables.
This guide explores various methods in Python to pad numbers with leading zeros or spaces, work with floats, and add plus signs, ensuring consistent and visually appealing formatting.
Formatting Integers to Fixed Width with f-strings
Formatted string literals (f-strings) provide a concise way to format numbers to a fixed width.
Padding with Leading Zeros
To left-pad a number with leading zeros, use the format specifier 0
followed by the desired width and the type specifier d
for integer:
my_int = 12
result = f'{my_int:03d}'
print(result) # Output: 012
result = f'{my_int:04d}'
print(result) # Output: 0012
- The format specifier
{my_int:03d}
pads the integer to a width of 3 digits, by adding zeros on the left. - You can change the number after the colon to specify the number of digits.
Padding with Leading Spaces
To left-pad a number with spaces, use the width without the 0
or d
:
my_int = 12
result = f'{my_int:3}'
print(repr(result)) # Output: ' 12'
- In this case the number will be left aligned and space padded to match the width you provided.
- You can use the
repr()
to see the spaces.
Formatting Floats to a Fixed Width with f-strings
To format a float to a fixed length and with a specific number of decimal digits, use the format specifier N.Mf
:
my_float = 1.234567
result = f'{my_float:8.3f}'
print(repr(result)) # Output: ' 1.235'
- The
8
in:8.3f
specifies a total length of 8 characters, including the decimal point and digits after the decimal. - The
.3f
part specifies the number of digits after the decimal should be 3, rounding if needed.
Extracting N Digits from a Number Using String Slicing
To get N digits from a number, you can convert it to a string and then perform string slicing to get a slice of the number, which is represented as a string:
result = str(1234567)[:3]
print(result) # Output: 123
Formatting Integers to a Fixed Width with str.zfill()
The str.zfill()
method left-pads a string with zeros to a specified width:
my_int = 12
result = str(my_int).zfill(3)
print(result) # Output: 012
result = str(my_int).zfill(4)
print(result) # Output: 0012
- First, the number is converted to a string.
- Then
str.zfill()
is called to pad the string on the left to match the given width, using the character0
. - If the width you provide is less than the length of the string, the string will be returned as is.
Formatting a List of Floats to a Fixed Width
To format a list of floats, you can either use list comprehensions or for
loops.
Using List Comprehensions
To format a list of floats to a fixed width use a list comprehension with formatted strings:
my_list = [1.23, 2.34, 4.56, 5.67]
result = [f'{item:5.1f}' for item in my_list]
print(result) # Output: [' 1.2', ' 2.3', ' 4.6', ' 5.7']
- The
f'{item:5.1f}'
format specifier formats every item to 5 digits with 1 digit after the decimal point.
Using a For Loop
You can also use a for loop:
my_list = [1.23, 2.34, 4.56, 5.67]
new_list = []
for item in my_list:
new_list.append(f'{item:5.1f}')
print(new_list) # Output: [' 1.2', ' 2.3', ' 4.6', ' 5.7']
- The
for
loop iterates over the list of numbers and formats them using f-strings. - The formatted numbers are appended to the new list.
Formatting Numbers with a Plus Sign
To display the plus sign for positive numbers, use the +
format specifier:
my_int = 3479
result = f'{my_int:+}'
print(result) # Output: +3479
my_float = 3.479567
result = f'{my_float:+.2f}'
print(result) # Output: +3.48
- The
+
after the colon indicates that the sign should always be shown, whether the number is positive or negative. - You can use this in combination with the float format specifiers.