Добавить лидирующие нули python

Добавить лидирующие нули python

Last updated: Feb 19, 2023
Reading time · 3 min

banner

# Table of Contents

# Add leading zeros to a number in Python

To add leading zeros to a number:

  1. Use the str() class to convert the number to a string.
  2. Use the str.zfill() method to add leading zeros to the string.
  3. 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.

Читайте также:  Php удалить куки браузера

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.

Источник

Display a Number With Leading Zeros in Python

Display a Number With Leading Zeros in Python

  1. Use the rjust() Function to Display a Number With Leading Zeros in Python
  2. Use the str.zfill() Function to Display a Number With Leading Zeros in Python
  3. Use String Formatting With the Modulus (%) Operator to Display a Number With Leading Zeros in Python
  4. Use String Formatting With the str.format() Function to Display a Number With Leading Zeros in Python
  5. Use String Formatting With f-strings to Display a Number With Leading Zeros in Python

Storing and displaying numbers with leading zeros is a crucial aspect as it significantly helps in accurately converting a number from one number system to another.

This tutorial discusses the different ways you can execute to display a number with leading zeros in Python.

Use the rjust() Function to Display a Number With Leading Zeros in Python

The rjust() function adds padding to the left side of a string. Padding, in simple terms, is the injection of non-informative characters to the left or the right side of a given string, which adds no additional value to the initial string. We can use string padding to display leading zeros in a Python program.

The rjust() function contains two parameters: width and fillchar . Out of these two, the width parameter is mandatory and is utilized to specify the length of the given string after the padding process is completed. On the other hand, the fillchar parameter is optional and represents the character that we want to pad the string with.

Here, we have an example program where we need to display the numbers, 1 and 10 , with leading zeros in each of the explained methods of this tutorial. The amount of padding required can be manually specified with the rjust() function.

The following code uses the rjust() function to display a number with leading zeros in Python.

a = [1, 10] for num in a:  print (str(num).rjust(2, '0')) 

The code above provides the following output.

Use the str.zfill() Function to Display a Number With Leading Zeros in Python

The str.zfill(width) function is utilized to return the numeric string; its zeros are automatically filled at the left side of the given width , which is the sole attribute that the function takes. If the value specified of this width parameter is less than the length of the string, the filling process does not occur.

The following code uses the str.zfill() function to display a number with leading zeros in Python.

print(str(1).zfill(2)) print(str(10).zfill(2)) 

The code above provides the following output.

The str.zfill() function is exclusively designed to pad a string with zeros towards its left side. It is an excellent choice and a highly recommended method in this case.

Use String Formatting With the Modulus (%) Operator to Display a Number With Leading Zeros in Python

The modulus % sign, sometimes even referred to as the string formatting or interpolation operator, is one of the few ways to implement string formatting in Python. Being the oldest of the ways you can implement string formatting, it works without any problems on almost all the versions of Python that are currently available for use on the internet.

The % sign and a letter representing the conversion type are marked as a placeholder for the variable.

The following code uses the string formatting with the modulus (%) operator to display a number with leading zeros in Python.

print ("%02d" % (1,)) print ("%02d" % (10,)) 

The code above provides the following output.

In the code above, the number 02 written after the % sign sets the text width to be displayed and adjusted for the leading zeros, and the d variable denotes the conversion type.

This method makes it easy to conduct the operation for displaying a number with leading zeros. Still, it affects the readability of the code and sometimes makes it more difficult to understand.

Use String Formatting With the str.format() Function to Display a Number With Leading Zeros in Python

Yet another way to implement string formatting in Python is by using the str.format() function. It utilizes the curly <> brackets to mark the place where the variables need to be substituted in the print statement.

The str.format() function was introduced in Python 2.6 and can be used in all Python versions released after that up to Python 3.5. This function is incredibly popular among coders, and the programmers recommend this way to implement string formatting due to its very efficient handling in formatting complex strings.

The following code uses string formatting with the str.format() function to display a number with leading zeros in Python.

print(" ".format(1)) print(" ".format(10)) 

The code above provides the following output.

In the program above, the content after the colon sign specifies the width and data type conversion; the curly brackets <> act as a placeholder.

Use String Formatting With f-strings to Display a Number With Leading Zeros in Python

Being introduced with Python 3.6, it is relatively the newest method in Python to implement string formatting. Additionally, it can be used in the latest versions of Python.

It is more efficient for implementing string formatting than the other two previous methods, the % operator and the str.format() function, as this one is quicker and simpler to understand. It also helps in implementing string formatting in Python at a faster rate than the other two.

The following code uses string formatting with f-strings to display a number with leading zeros in Python.

The code above provides the following output:

In the program above, the string width and data conversion type are specified after the colon sign within the placeholder.

When it comes to using string formatting to pad the string with leading zeros, the use of f-strings is recommended by professionals more than its other two methods. It is more concise, less prone to errors, and certainly improves the readability of the program.

Vaibhhav is an IT professional who has a strong-hold in Python programming and various projects under his belt. He has an eagerness to discover new things and is a quick learner.

Related Article — Python String

Related Article — Python Number

Copyright © 2023. All right reserved

Источник

Python String zfill() Method

Fill the string with zeros until it is 10 characters long:

Definition and Usage

The zfill() method adds zeros (0) at the beginning of the string, until it reaches the specified length.

If the value of the len parameter is less than the length of the string, no filling is done.

Syntax

Parameter Values

More Examples

Example

Fill the strings with zeros until they are 10 characters long:

a = «hello»
b = «welcome to the jungle»
c = «10.000»

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

Оцените статью