How to Format a Number with Leading Zeros in Python

78 views

How to Format a Number with Leading Zeros in Python

How to Format a Number with Leading Zeros in Python

I need to format a number to have a specific length by adding leading zeros. How can I achieve this in Python?

solveurit24@gmail.com Changed status to publish February 16, 2025
0

String formatting can be used to add leading zeros to a number.

  1. Using zfill() Method:
    • Pads the string on the left with zeros.
  2. Code Example:

    number = 5
    formatted_number = str(number).zfill(3)
    print(formatted_number)  # Output: "005"
    


  3. Using format() Method:
    • Provides more flexibility and control over formatting.
  4. Alternative Code:

    number = 5
    print("{:04d}".format(number))  # Output: "0005"


  5. Using F-Strings:
    • Modern and concise method in Python 3.6+.
  6. Another Approach:

    number = 5
    print(f"{number:04}")  # Output: "0005"
    


  7. Explanation:
    • zfill() is simple for adding leading zeros.
    • format() and f-strings offer more formatting options and are often preferred for their readability.
solveurit24@gmail.com Changed status to publish February 16, 2025
0