How to Add leading Zeros to a Number in Python

How to Add leading Zeros to a Number in Python

To add leading zeros to a number in Python, you can utilize the string's str.zfill() method or string formatting. Here's how you can do it:

  1. Using str.zfill():

    The zfill() method pads a string representation of a number with zeros (0) until it reaches the specified width.

    number = 42 padded_number = str(number).zfill(5) print(padded_number) # 00042 
  2. Using str.format():

    number = 42 padded_number = "{:05}".format(number) print(padded_number) # 00042 

    In this example, {:05} means that the number should be formatted to have at least a width of 5 characters, padding with zeros if necessary.

  3. Using f-strings (Python 3.6+):

    number = 42 padded_number = f"{number:05}" print(padded_number) # 00042 

Choose the method that best suits your version of Python and your personal preference.


More Tags

aws-iot entities scriptlet amazon-web-services class-attributes double powerbi-desktop substring hashtag angular-reactive-forms

More Programming Guides

Other Guides

More Programming Examples