- How to add zeros before a number in Python
- Python Add Zeros Before Number
- Method 1: Using the Python built-in str.zfill() function
- Method 2: Using Python String formatting
- Method 3: Using Python rjust() function
- Conclusion
- Python format string leading zeros
- # Table of Contents
- # Add leading zeros to a number in Python
- # The zfill() method handles the leading sign prefix
- # Using a formatted string literal to add leading zeros to a number
- # Add leading zeros to a number using str.format()
- # Add leading zeros to a number using str.rjust()
- # Add leading zeros to a number using format()
- Python Pad a String with Leading Zeros
- How to Pad a String With Leading Zeros in Python?
- Method 1: Pad a String With Leading Zeros in Python Utilizing “f-string” Method
- Example
- Method 2: Pad a String With Leading Zeros in Python Utilizing “format()” Method
- Example
- Method 3: Pad a String With Leading Zeros in Python Utilizing “zfill()” Method
- Example
- Method 4: Pad a String With Leading Zeros in Python Utilizing “rjust()” Method
- Example
- Method 5: Pad a String With Leading Zeros in Python Utilizing “ljust()” Method
- Example
- Conclusion
- About the author
- Maria Naz
How to add zeros before a number in Python
In this Python Article, we’ll explore various methods of how you can add zeros before a number in Python.
Python Add Zeros Before Number
One common scenario in data processing and manipulation is the need to add leading zeros to a number. For instance, you might have a series of data that you need to standardize with the same number of digits for a report or a system.
Let’s discuss various methods of adding zeros before numbers in Python:
Method 1: Using the Python built-in str.zfill() function
Python’s string method zfill() is a straightforward way to add leading zeros. It takes one argument – the total number of characters you want the string to be. It adds zeros at the beginning of the string until it reaches the desired length.
Example: If we have the state code 5 and we want to ensure it is two digits:
state_code = 5 print(str(state_code).zfill(2))
In the above example, we converted the integer to a string with str(state_code) and then used zfill(2) to pad it to two characters with leading zeros.
Method 2: Using Python String formatting
Python string formatting offers a more flexible and powerful way to transform data into strings. The format() function or f-string formatting can be used to add leading zeros.
Example: In a case where you need to prepare a series of numbered reports, and you want all report numbers to have three digits:
report_number = 7 print(''.format(report_number))
The :03d inside the curly brackets <> is a format specification for the format function. 0 is the character for padding, 3 is the width or the total number of characters, and d stands for integer.
If you prefer using f-string formatting:
Method 3: Using Python rjust() function
The rjust() string method in Python right-justifies the string and fills in the space with a specified character, which is a space by default. In this case, we’ll use ‘0’ as the fill character.
Example: Imagine you have a series of product codes in a retail system, and they need to have a standard length of five digits:
product_code = 57 print(str(product_code).rjust(5, '0'))
This code will print the number right-justified, filling it with zeros up to three characters.
Conclusion
In Python, there are various ways to add leading zeros to a number, with each method having its own advantages. The zfill() function is easy and straightforward to use for simple padding. The string formatting option offers more power and flexibility, and rjust() can also be used for right-justifying and padding a number.
You may like the following Python tutorials:
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.
Python format string leading zeros
Last updated: Feb 19, 2023
Reading time · 4 min
# Table of Contents
# Add leading zeros to a number in Python
To add leading zeros to a number:
- Use the str() class to convert the number to a string.
- Use the str.zfill() method to add leading zeros to the string.
- The method takes the width of the string and pads it with leading zeros.
Copied!num = 246 result_1 = str(num).zfill(5) print(result_1) # 👉️ '00246' result_2 = str(num).zfill(6) print(result_2) # 👉️ '000246'
We used the str() class to convert the number to a string.
This is necessary because adding leading zeros to a number causes a SyntaxError .
The str.zfill method takes the width of the string and left-fills the string with 0 digits to make it of the specified width.
Copied!num = 13 result_1 = str(num).zfill(3) print(result_1) # 👉️ '013' result_2 = str(num).zfill(4) print(result_2) # 👉️ '0013'
Converting the number 13 to a string gives us a string with a length of 2 .
Passing 3 as the width to the zfill() method means that the string will get left-filled with a single 0 digit.
# The zfill() method handles the leading sign prefix
The str.zfill() method handles a leading sign prefix (e.g. + or — ) by inserting the padding after the sign.
Copied!num = -13 result_1 = str(num).zfill(3) print(result_1) # 👉️ '-13' result_2 = str(num).zfill(4) print(result_2) # 👉️ '-013'
Note that the sign counts toward the width of the string.
If the specified width is less than or equal to the length of the original string, then the original string is returned.
Copied!num = 13 result_1 = str(num).zfill(2) print(result_1) # 👉️ '13' result_2 = str(num).zfill(1) print(result_2) # 👉️ '13'
The number in the example has a length of 2 , so trying to fill it to 2 characters doesn’t have an effect.
# Using a formatted string literal to add leading zeros to a number
Alternatively, you can use a formatted string literal to add leading zeros to a number.
Copied!num = 13 result_1 = f'num:04>' print(result_1) # 👉️ '0013' result_2 = f'num:05>' print(result_2) # 👉️ '00013'
We don’t have to use the str() class to convert the integer to a string as the conversion is done for us automatically.
Formatted string literals (f-strings) let us include expressions inside of a string by prefixing the string with f .
Copied!my_str = 'is subscribed:' my_bool = True result = f'my_str> my_bool>' print(result) # 👉️ is subscribed: True
Make sure to wrap expressions in curly braces — .
Formatted string literals also enable us to use the format specification mini-language in expression blocks.
The first digit after the colon is the fill value and the second is the width of the string.
Copied!num = 13 result_1 = f'num:04>' print(result_1) # 👉️ '0013'
This approach also works if the width of the string is stored in a variable.
Copied!num = 13 width_of_string = 4 result_1 = f'num:0width_of_string>>' print(result_1) # 👉️ '0013'
# Add leading zeros to a number using str.format()
You can also use the str.format() method to add leading zeros to a number.
Copied!num = 13 result_1 = ''.format(num) print(result_1) # 👉️ '0013' result_2 = ''.format(num) print(result_2) # 👉️ '00013'
The str.format method performs string formatting operations.
Copied!first = 'bobby' last = 'hadz' result = "Name: <> <>".format(first, last) print(result) # 👉️ "Name: bobby hadz"
The string the method is called on can contain replacement fields specified using curly braces <> .
# Add leading zeros to a number using str.rjust()
You can also use the str.rjust() method to add leading zeros to a number.
Copied!num = 13 result_1 = str(num).rjust(4, '0') print(result_1) # 👉️ '0013' result_2 = str(num).rjust(5, '0') print(result_2) # 👉️ '00013'
The str.rjust method pads the beginning of the string to the specified width with the provided fill character.
The str.rjust method takes the following 2 arguments:
Name | Description |
---|---|
width | The total length of the padded string |
fillchar | The fill character to pad the string with |
Copied!num = 13 result_1 = str(num).rjust(4, '0') print(result_1) # 👉️ '0013'
The first argument is the width of the padded string and the second is the fill character ( 0 in our case).
Notice that we had to convert the number to a string using the str() class.
This is necessary because rjust() is a method implemented on strings.
# Add leading zeros to a number using format()
You can also use the format() function to add leading zeros to a number.
Copied!num = 13 result = format(num, '03') print(result) # 👉️ 013 result = format(num, '04') print(result) # 👉️ 0013 result = format(num, '05') print(result) # 👉️ 00013
The first argument the format() function takes is the value and the second is a string used to format the value.
The first digit is the fill character ( 0 ) and the second is the total width of the string.
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
Python Pad a String with Leading Zeros
A string is the object of the “String” class that is a collection of characters represented by a single word and the class has several methods to manipulate and access the strings. In Python, we don’t need to declare strings explicitly, we are allowed to directly assign them to a literal. Moreover, we can pad the string with numbers which can be needed for a few reasons. For instance, to make a numeric string for easy sorting, to make a number look more readable, and many more.
This post will talk about different methods for padding any string with leading zeros in Python.
How to Pad a String With Leading Zeros in Python?
Below provided methods are used to pad a string with leading zeros in Python:
Method 1: Pad a String With Leading Zeros in Python Utilizing “f-string” Method
The most recent version of Python provides a method “f-string” for quick string formatting. It can be used for padding a string with leading zeros in Python.
Example
Declare two string variables named “string1” and “string2”. Then, initialize with values:
Now, call the “print()” method with the “f-string” to pad the provided string with leading zeros. Here, the value “10” indicates that increase in the length of provided string by using zeros:
As you can see, our provided strings have the “5” and “4” length, which are now increased to “10” and “8” respectively by leading zeros:
Method 2: Pad a String With Leading Zeros in Python Utilizing “format()” Method
Another way to pad a Python string with all zeros is the “format()” method. The “format()” method can format any provided string to display them in our required format based on some patterns.
Example
Call the “format()” method inside the print statement and pass a desired string as an argument along with the required length of string which needs to replace with zeros:
print ( ‘<:0>10>’ . format ( string1 ) )
print ( ‘8>’ . format ( string2 ) )
Method 3: Pad a String With Leading Zeros in Python Utilizing “zfill()” Method
For padding a string with leading zeros in Python, the “zfill()” method can be used. It takes a number providing the required length of any Python string as an argument and adds zeros at the left side of the string until it is of the specified length. In short, it adds the “0” at the left side of any provided string.
Example
Call the “zfill()” method and pass the desired number of string length inside the “print()” function and print its result:
Method 4: Pad a String With Leading Zeros in Python Utilizing “rjust()” Method
If you want to pad a string with zeros only at the left side of any string until the string is of the provided length, the “rjust()” can be used.
Example
Use the “rjust()” method along with the required length of string and the number which needs to be added to make the string according to the desired length as an argument. Then, pass them to the “print()” method:
print ( string1. rjust ( 10 , «0» ) )
print ( string2. rjust ( 8 , «0» ) )
It can be observed that the provided string contains zeros at the left side of it:
Method 5: Pad a String With Leading Zeros in Python Utilizing “ljust()” Method
The “ljust()” method is used to add zeros at the right side of any string until the string is of the provided length. For a better understanding, check out the following implementation of this method.
Example
Call the “ljust()” method along with the required argument inside the “print()” method:
print ( string1. ljust ( 10 , «0» ) )
print ( string2. ljust ( 8 , «0» )
That’s it! We have compiled multiple methods for padding the Python string with leading zeros.
Conclusion
To pad the string with leading zeros in Python, the “f-string“, the “format()” method, the “zfill()” method, the “rjust()” method, and the “ljust()” method can be used. All specified methods are inbuilt methods of Python. This post described multiple methods to pad any Python string with leading zeros.
About the author
Maria Naz
I hold a master’s degree in computer science. I am passionate about my work, exploring new technologies, learning programming languages, and I love to share my knowledge with the world.