The format()
function formats numbers, strings, and other values into a specific format. It’s useful for controlling decimal places, aligning text, adding commas, and creating well-structured output.
Example
num = 1234.56789
formatted = format(num, ".2f")
print(formatted)
# Output: 1234.57
This rounds the number to 2 decimal places.
Syntax
format(value, format_spec)
- value → The number or string to format.
- format_spec → A string specifying the format.
1. Formatting Numbers with Decimal Places
Control decimal precision easily.
num = 3.1415926535
print(format(num, ".3f"))
# Output: 3.142
Rounds the number to 3 decimal places.
2. Adding Commas to Large Numbers
Make numbers easier to read.
big_number = 1234567890
print(format(big_number, ","))
# Output: 1,234,567,890
Useful for financial reports and data presentation.
3. Formatting Percentages
Convert a decimal into a percentage.
percentage = 0.75
print(format(percentage, ".0%"))
# Output: 75%
Great for displaying percentages cleanly.
4. Aligning Text Output
Align text to the left, right, or center.
text = "Python"
print(format(text, "<10")) # Left align
print(format(text, ">10")) # Right align
print(format(text, "^10")) # Center align
Perfect for creating tables and structured output.
5. Formatting Binary, Octal, and Hexadecimal
Convert numbers to different bases.
num = 255
print(format(num, "b")) # Binary → Output: 11111111
print(format(num, "o")) # Octal → Output: 377
print(format(num, "x")) # Hexadecimal → Output: ff
Useful for working with low-level data or bit manipulation.
Key Notes
- ✔ Controls decimal places, percentages, and number formatting.
- ✔ Helps in text alignment and structured output.
- ✔ Converts numbers to binary, octal, and hexadecimal.
- ✔ Makes large numbers readable with commas.
By using format()
, you can improve the readability and presentation of data, making your output cleaner and more professional. 🚀