Formatting numbers in Python is essential for displaying numerical data in a readable and structured way.
Whether you're dealing with currency, percentages, or large numbers, Python provides multiple ways to format numbers effectively.
Basic Number Formatting with format()
The format()
method provides a flexible way to format numbers:
num = 1234.5678
formatted = "{:.2f}".format(num)
print(formatted)
Explanation: This formats the number to 2 decimal places.
Output:
1234.57
Using F-Strings for Number Formatting
For me, f-strings offer a concise and more logical way to format numbers:
num = 1234.5678
print(f"Formatted number: {num:.2f}")
Explanation: The :.2f
ensures two decimal places.
Output:
Formatted number: 1234.57
Comparing format() vs. F-Strings
Both format()
and f-strings achieve the same result, but for me, f-strings provide a more readable and modern approach. Unlike format()
, which requires calling a method on a string, f-strings allow direct interpolation of variables, making the code cleaner and easier to understand for beginners.
Example comparison:
name = "Alice"
age = 30
# Using format()
print("My name is {} and I am {} years old.".format(name, age))
# Using f-strings
print(f"My name is {name} and I am {age} years old.")
Output:
My name is Alice and I am 30 years old.
My name is Alice and I am 30 years old.
Why use f-strings?
-
More readable: Variables are embedded directly within the string.
-
More efficient: Faster execution compared to
.format()
. -
Easier to write: No need to remember placeholder positions.
Formatting Large Numbers with Commas
You can format large numbers with commas for better readability:
big_number = 1000000
print(f"{big_number:,}")
Explanation: The :,
adds commas as thousand separators.
Output:
1,000,000
Formatting as Currency
To display numbers as currency:
price = 1999.99
print(f"${price:,.2f}")
Explanation: The :,.2f
ensures two decimal places and includes commas.
Output:
$1,999.99
Displaying Percentages
Convert decimal values to percentages:
completion = 0.85
print(f"Task completion: {completion:.0%}")
Explanation: The :.0%
converts to a percentage with no decimal places.
Output:
Task completion: 85%
Formatting in Scientific Notation
For very large or small numbers, use scientific notation:
num = 0.0001234
print(f"{num:.2e}")
Explanation: The :.2e
formats the number in scientific notation with 2 decimal places.
Output:
1.23e-04
Aligning Numbers in Output
Align numbers for cleaner table formatting:
num1, num2 = 23, 4567
print(f"{num1:>6}")
print(f"{num2:>6}")
Explanation: The >6
right-aligns numbers within a field of width 6.
Output:
23
4567
Key Takeaways
-
Use
.2f
to control decimal places -
Use
:,
for thousands separators. -
Use
.0%
for percentage formatting. -
Use
.2e
for scientific notation. -
Use alignment specifiers for structured output.
-
Prefer f-strings over
format()
for better readability and efficiency in your Python projects.
Practice Exercise
Here's a simple challenge, try formatting a number as currency and as a percentage in your preferred Python editor:
amount = 2500.75
rate = 0.065
print(f"Total: ${amount:,.2f}")
print(f"Interest Rate: {rate:.1%}")
Wrapping Up
Python provides multiple ways to format numbers efficiently, whether you need decimals, currency, or scientific notation. While the format()
method is still widely used, f-strings offer a more modern and intuitive approach, making them the preferred choice for most new Python projects. Mastering these techniques will improve your output formatting and make your data more presentable. Happy coding!