Last updated: Apr 9, 2024
Reading timeยท6 min
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.
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'
The first example uses a formatted string literal to format a number to a fixed width.
my_int = 12 result = f'{my_int:03d}' print(result) # ๐๏ธ '012' result = f'{my_int:04d}' print(result) # ๐๏ธ '0012'
: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.
f
.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.
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
You can use the same approach if you need to format the integer into a fixed length string with leading spaces.
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.
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.
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.
result = str(1234567)[:3] print(result) # ๐๏ธ 123
The code sample returns a string containing the first 3 digits of the number.
This is a three-step process:
str()
class to convert the number to a string.str.zfill()
method to format the string to the specified width.zfill()
method left-fills the string with 0
digits to make it of the
specified length.my_int = 12 result = str(my_int).zfill(3) print(result) # ๐๏ธ '012' result = str(my_int).zfill(4) print(result) # ๐๏ธ '0012'
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.
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.
To format a list of floating-point numbers to a fixed width:
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']
We used a list comprehension to iterate over the list of floating-point numbers.
On each iteration, we use a formatted string literal to format the float to a fixed length of 5 with 1 decimal place.
for
loopAlternatively, you can 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}') # ๐๏ธ 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']
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.
You can also use a formatted string literal to format a number with a plus sign.
# โ 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
We used a formatted string literal to format a number with a plus sign.
f
.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.
my_int = 3479 result = f'{my_int:+}' print(result) # ๐๏ธ +3479
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.
num = 0 result = f'{num:{"+" if num else ""}}' print(result) # ๐๏ธ 0
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.
num = -3479 result = f'{num:{"+" if num else ""}}' print(result) # ๐๏ธ -3479
+
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.
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.
You can learn more about the related topics by checking out the following tutorials: