Format a Number to a fixed Width in Python

avatar
Borislav Hadzhiev

Last updated: Apr 9, 2024
6 min

banner

# Table of Contents

  1. Format a number to a fixed width in Python
  2. Format a number to a fixed width using str.zfill()
  3. Format a list of floating-point numbers to fixed width
  4. Format a number with a plus (+) sign in Python

# Format a number to a fixed width in Python

Use a formatted string literal to format a number to a fixed width, e.g. result = f'{my_int:03d}'.

The formatted string literal will format the number to the specified width by prefixing it with the necessary number of leading zeros.

main.py
my_int = 12 # โœ… format integer to a fixed width of 3 result = f'{my_int:03d}' print(result) # ๐Ÿ‘‰๏ธ '012' # โœ… format integer to a fixed width of 4 result = f'{my_int:04d}' print(result) # ๐Ÿ‘‰๏ธ '0012' # โœ… format integer to a fixed width of 3 (with leading spaces) result = f'{my_int:3}' print(repr(result)) # ๐Ÿ‘‰๏ธ ' 12' # ----------------------------------- my_float = 1.234567 # โœ… format float to a fixed width of 8 with 3 digits after the decimal result = f'{my_float:8.3f}' print(repr(result)) # ๐Ÿ‘‰๏ธ ' 1.235' # ----------------------------------- # โœ… using str.zfill() result = str(my_int).zfill(3) print(result) # ๐Ÿ‘‰๏ธ '012' result = str(my_int).zfill(4) print(result) # ๐Ÿ‘‰๏ธ '0012'

format number to fixed width

The code for this article is available on GitHub

The first example uses a formatted string literal to format a number to a fixed width.

main.py
my_int = 12 result = f'{my_int:03d}' print(result) # ๐Ÿ‘‰๏ธ '012' result = f'{my_int:04d}' print(result) # ๐Ÿ‘‰๏ธ '0012'
The :03d syntax is used to pad the integer with leading zeros to a fixed width of 3 digits.

The first f-string formats the number to a width of 3 digits and the second to a width of 4 digits.

If necessary, leading zeros are added to format the number to the specified width.

Formatted string literals (f-strings) let us include expressions inside of a string by prefixing the string with f.
main.py
my_str = 'The number is:' my_int = 5000 result = f'{my_str} {my_int}' print(result) # ๐Ÿ‘‰๏ธ The number is: 5000

Make sure to wrap expressions in curly braces - {expression}.

Formatted string literals also enable us to use the format-specific mini-language in expression blocks.

main.py
hours = 8 minutes = 24 seconds = 3 result = f'The time is: {hours:02d}:{minutes:02d}:{seconds:02d} {"pm" if hours > 12 else "am"}' print(result) # ๐Ÿ‘‰๏ธ The time is: 08:24:03 am
The code for this article is available on GitHub

You can use the same approach if you need to format the integer into a fixed length string with leading spaces.

main.py
my_integer = 8 result = f'{my_integer:3}' print(repr(result)) # ๐Ÿ‘‰๏ธ ' 8'

The integer in the example consists of a single digit, so it gets left-padded with 2 spaces.

You can also use a formatted string literal if you need to format a float to a fixed width.
main.py
my_float = 1.234567 # โœ… format float to fixed length of 8 with 3 digits after the decimal result = f'{my_float:8.3f}' print(repr(result)) # ๐Ÿ‘‰๏ธ ' 1.235'

The example formats the float to a width of 8 with 3 digits after the decimal.

The string gets left-padded with spaces to format the float to the specified length.

If you just need to perform string formatting with numbers, include the variables in curly braces.

main.py
num1 = 2 num2 = 6 result = f'{num1} + {num2} = {num1 + num2}' print(result) # ๐Ÿ‘‰๏ธ '2 + 6 = 8'

If you only need to get N digits from a longer number, use string slicing.

main.py
result = str(1234567)[:3] print(result) # ๐Ÿ‘‰๏ธ 123

The code sample returns a string containing the first 3 digits of the number.

# Format a number to a fixed width using str.zfill()

This is a three-step process:

  1. Use the str() class to convert the number to a string.
  2. Use the str.zfill() method to format the string to the specified width.
  3. The zfill() method left-fills the string with 0 digits to make it of the specified length.
main.py
my_int = 12 result = str(my_int).zfill(3) print(result) # ๐Ÿ‘‰๏ธ '012' result = str(my_int).zfill(4) print(result) # ๐Ÿ‘‰๏ธ '0012'

format number to fixed width using str zfill

The code for this article is available on GitHub

The str.zfill() method takes the width of the string and left-fills the string with 0 digits to make it of the specified width.

Converting the number 12 to a string gives us a string with a length of 2.

Passing 3 as the width to the zfill() method means that the string will get left-filled with a single 0 digit.

The str.zfill() method handles a leading sign prefix (e.g. + or -) by inserting the padding after the sign.

main.py
num = -12 result_1 = str(num).zfill(3) print(result_1) # ๐Ÿ‘‰๏ธ '-12' result_2 = str(num).zfill(4) print(result_2) # ๐Ÿ‘‰๏ธ '-012'

Note that the sign counts toward the width of the string.

If the specified width is less than or equal to the length of the original string, then the original string is returned.

# Format a list of floating-point numbers to a fixed width

To format a list of floating-point numbers to a fixed width:

  1. Use a list comprehension to iterate over the list.
  2. Use a formatted string literal to format each float to a fixed width.
  3. The new list will contain strings storing the float values, formatted to the specified width.
main.py
my_list = [1.23, 2.34, 4.56, 5.67] # ๐Ÿ‘‡๏ธ format each float to fixed length of 5 with 1 decimal place result = [f'{item:5.1f}' for item in my_list] print(result) # ๐Ÿ‘‰๏ธ [' 1.2', ' 2.3', ' 4.6', ' 5.7']

format list of floating point numbers to fixed width

The code for this article is available on GitHub

We used a list comprehension to iterate over the list of floating-point numbers.

List comprehensions are used to perform some operation for every element or select a subset of elements that meet a condition.

On each iteration, we use a formatted string literal to format the float to a fixed length of 5 with 1 decimal place.

# Format a list of floating-point numbers to a fixed width using for loop

Alternatively, you can use a for loop.

main.py
my_list = [1.23, 2.34, 4.56, 5.67] new_list = [] for item in my_list: new_list.append(f'{item:5.1f}') # ๐Ÿ‘‡๏ธ format each float in the list to fixed width of 5 with 1 decimal print(new_list) # ๏ธ ๐Ÿ‘‰๏ธ [' 1.2', ' 2.3', ' 4.6', ' 5.7']

format list of floating point numbers to fixed width using for loop

The code for this article is available on GitHub

We used a for loop to iterate over the list of floating-point numbers.

On each iteration, we format the current number to a fixed length of 5 with 1 decimal place and append the result to the new list.

# Format a number with a plus (+) sign in Python

You can also use a formatted string literal to format a number with a plus sign.

main.py
# โœ… Format integer with a plus sign my_int = 3479 result = f'{my_int:+}' print(result) # ๐Ÿ‘‰๏ธ +3479 # ----------------------------------- # โœ… Format floating-point number with a plus sign my_float = 3.479567 result = f'{my_float:+.2f}' print(result) # ๐Ÿ‘‰๏ธ +3.48

format number with plus sign

The code for this article is available on GitHub

We used a formatted string literal to format a number with a plus sign.

Formatted string literals (f-strings) let us include expressions inside of a string by prefixing the string with f.
main.py
var1 = 'bobby' var2 = 'hadz' result = f'{var1}{var2}' print(result) # ๐Ÿ‘‰๏ธ 'bobbyhadz'

Make sure to wrap expressions in curly braces - {expression}.

Formatted string literals also enable us to use the format specification mini-language in expression blocks.

main.py
my_int = 3479 result = f'{my_int:+}' print(result) # ๐Ÿ‘‰๏ธ +3479
The plus sign after the colon indicates that a sign should be used for both positive and negative numbers.

The default behavior is to only show the sign of the number if it is negative.

If you don't want to show a sign if the number is zero, use the ternary operator.

main.py
num = 0 result = f'{num:{"+" if num else ""}}' print(result) # ๐Ÿ‘‰๏ธ 0
The code for this article is available on GitHub

If the number is truthy, we return a string containing a plus, otherwise an empty string is returned.

Zero is the only number that is falsy, so a plus gets returned for any other value.

If the number is negative, a minus sign is shown.

main.py
num = -3479 result = f'{num:{"+" if num else ""}}' print(result) # ๐Ÿ‘‰๏ธ -3479
The plus + sign after the colon indicates that the sign of the number should be shown, regardless if the number is positive or negative.

You can use the same approach to format a floating-point number with a plus sign.

main.py
my_float = 3.479567 result = f'{my_float:+}' print(result) # ๐Ÿ‘‰๏ธ +3.479567 result = f'{my_float:+.2f}' print(result) # ๐Ÿ‘‰๏ธ +3.48

The first example formats the float with a plus sign and the second example formats it with a plus sign and rounds it to 2 digits after the decimal.

The digit after the period is the number of decimal places the float should have.

You can read about the format specification mini-language used in f-strings in this section of the docs.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev