In this tutorial, we will explore how to use f-strings in Python to format numbers. F-strings are a powerful tool for formatting strings and can be used to control the number of digits after the decimal point.
Introduction to F-Strings
F-strings were introduced in Python 3.6 as a new way to format strings. They provide a more readable and concise way to embed expressions inside string literals, using an f prefix before the string.
Basic Number Formatting
To format a number with f-strings, you can use the syntax f'{value:{format_spec}}'
. The format_spec
is where you specify how you want to format the number. For example, to display 2 digits after the decimal place, you would use .2f
.
a = 10.1234
print(f'{a:.2f}') # Output: '10.12'
Format Specification
The format_spec
is a string that specifies how to format the number. It consists of several parts:
fill
: The character to use for padding.align
: The alignment of the value (left, right, center).sign
: Whether to display a sign (+ or -) before the value.#
: A flag that changes the format of some types (e.g., hex, octal).0
: A flag that pads with zeros instead of spaces.width
: The minimum width of the formatted string.grouping_option
: The character to use for grouping digits (thousands separator).precision
: The number of digits after the decimal point.type
: The type of format (fixed-point, scientific notation, etc.).
Here are some examples:
# Fixed-point notation with 2 digits after the decimal place
print(f'{10.1234:.2f}') # Output: '10.12'
# Scientific notation with 3 digits after the decimal place
print(f'{10.1234:.3e}') # Output: '1.012e+01'
# Percentage with 2 digits after the decimal place
print(f'{0.1234:.2%}') # Output: '12.34%'
Advanced Formatting
You can also specify a width and alignment for the formatted string:
# Right-aligned, padded with spaces to a minimum width of 10 characters
print(f'{10.1234:>10.2f}') # Output: ' 10.12'
# Left-aligned, padded with zeros to a minimum width of 10 characters
print(f'{10.1234:<0=10.2f}') # Output: '000010.12'
Thousands Separator
To use a thousands separator (comma), you can specify it in the grouping_option
part:
# Fixed-point notation with a thousands separator and 2 digits after the decimal place
print(f'{10000.1234:,.2f}') # Output: '10,000.12'
Conclusion
F-strings provide a powerful way to format numbers in Python. With their flexible syntax and numerous options, you can easily control how your numbers are displayed.
Remember to always consult the official Python documentation for more information on f-strings and formatting strings.