Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to format numbers to strings in Python?
You can format numbers to strings in Python using several methods: the format() function, f-strings, and the % operator. Each approach allows you to control precision, width, and alignment.
Formatting Floating Point Numbers
Use the format() function to control decimal places and field width ?
nums = [0.555555555555, 1, 12.0542184, 5589.6654753]
for x in nums:
print("{:10.4f}".format(x))
The output of the above code is ?
0.5556
1.0000
12.0542
5589.6655
The format {:10.4f} means: 10 characters total width with 4 decimal places.
Formatting Integers
Format integers using the d format specifier ?
nums = [5, 20, 500]
for x in nums:
print("{:d}".format(x))
5 20 500
Adding Padding to Numbers
Specify field width to add padding and align numbers ?
nums = [5, 20, 500]
for x in nums:
print("{:4d}".format(x))
5 20 500
Using F-strings (Python 3.6+)
F-strings provide a more readable syntax for formatting ?
nums = [0.555555, 12.0542, 5589.6655]
for x in nums:
print(f"{x:10.4f}")
0.5556
12.0542
5589.6655
Comparison of Methods
| Method | Syntax | Best For |
|---|---|---|
format() |
"{:.2f}".format(x) |
Python 2/3 compatibility |
| F-strings | f"{x:.2f}" |
Modern Python (3.6+) |
| % operator | "%.2f" % x |
Legacy code |
Conclusion
Use f-strings for modern Python applications as they're more readable and performant. The format() function remains useful for compatibility with older Python versions.
Advertisements
