- How to Add Leading Zeros to a Number in Python?
- What are the methods to Add Leading Zeros to a number?
- Method 1: Using str.zfill() method
- Example
- Output
- Method 2: Using the rjust() method
- Example
- Output
- Method 3: Using string formatting
- Example
- Output
- Method 4: Using f-string
- Example
- Output
- Conclusion
- Python zeros before number
- # 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()
- 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
How to Add Leading Zeros to a Number in Python?
While working with numbers in Python, it is often necessary to add leading zeros to a number. Adding leading zeros to a number is important when you are dealing with formatted data or when you need to ensure that a certain number of digits are present in a number, or in a more readable form. In this article, we will explore different methods that can be used to add leading zeros to a number in Python.
What are the methods to Add Leading Zeros to a number?
In programming, it’s often necessary to format numerical data in a specific way to meet certain requirements for example adding leading zeros to a number, which means placing zeros before the actual value of the number to make it a fixed width.
Python is a versatile programming language that offers multiple libraries and methods to add leading zeros to a number. Below are some of thepopular methods to perform the task.
Method 1: Using str.zfill() method
One method to add leading zeros to a number is to convert the number to a string first and then use the zfill() method to add the leading necessary zeros. The zfill() method takes a single argument, which is the width of the resulting string or the string that will come as output. If the original string is shorter than the specified width, then the zfill() method adds zeros to the beginning of the string until it reaches the specified width.
Where stri is the original string.
Example
number = 50 desired_width = 5 #first convert thenumber to string then use zfil method number_str = str(number).zfill(desired_width) print("Number after leading zeros: ") print(number_str)
Output
Number after leading zeros: 00050
In the above example, we start with the number 50 and convert it to a string using the str() function. We then use the zfill() function to add leading zeros to the string until it has a width of 5. The resulting string is “00050”.
Method 2: Using the rjust() method
The other method to add leading zeros to the number is to use the rjust() method which can be used to right justify a string and fill the remaining space with a specified character. To add leading zeros to a number, we can convert the number to a string and then call the rjust() method with the desired width and fill character.
Example
number = 50 desired_width = 5 number_str = str(number).rjust(desired_width, "0") print("Number after leading zeros: ") print(number_str)
Output
Number after leading zeros: 00050
In the above example, we have first converted the number into a string and then we used the rjust() method which has two parameters one is for the width and the other is the value that we will use to fill to add leading zeros to the number 50.
Method 3: Using string formatting
Another method to add leading zeros to a number is to use string formatting. Python’s string formatting syntax allows you to specify the width and precision of a number, among other things. To add leading zeros to a number, we can use the “0” character as a fill character and specify the desired width.
Example
number = 50 desired_width = 5 number_str = "<>>".format(number, desired_width) print("Number after leading zeros: ") print(number_str)
Output
Number after leading zeros: 00050
In the above example, we use the string formatting syntax to format the number 50 as a string with a width of 5 which adds leading zeros. The “<>>” part of the string formatting expression specifies that we want to fill the string with zeros (“0”), that we want to right-align the number(“>”), and that we want to specify the width using the second argument to the format() method.
Method 4: Using f-string
Another method to add leading zeros to a string is to use the f-string syntax. From Python 3.6, a new string formatting syntax called f-string was introduced. The f-string provides a simpler and more intuitive way to format as compared to the older string formatting syntax. To add leading zeros to a number we can simply include the desired width and fill the character with zeros in the f-string expression.
Example
number = 50 desired_width = 5 print("Number after leading zeros: ") number_str = f">" print(number_str)
Output
Number after leading zeros: 00050
In the above example, we use the f-string syntax to format the number 50 as a string with a width of 5 and leading zeros. The f-string expression «>» specifies that we want to fill the string with zeros (“0”), right-align the number (“>”), and specify the width using the variable “desired_width”.
Conclusion
In conclusion, there are different methods to add leading zeros to a number in Python. We have explored different methods to add leading zeros to a number like, zfill() method, string formatting, f-strings or rjust() method, it is important to understand how each method works and choose the one that best suits the needs.
Python zeros before number
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.
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.