Python format pad zeros

Pad strings and numbers with zeros in Python (Zero-padding)

This article explains how to perform zero-padding on various data types such as strings ( str ) and integers ( int ) in Python.

Right-justified and zero-filled: zfill()

Specify the length of the returned string. The original string will be right-justified, and the left side will be filled with zeros.

s = '1234' print(s.zfill(8)) # 00001234 print(type(s.zfill(8))) # 

If a value smaller than the length of the original string is given, the original string will be returned as it is.

If a leading sign prefix ( — , + ) exists, the string is filled with zeros after the sign.

s = '-1234' print(s.zfill(8)) # -0001234 s = '+1234' print(s.zfill(8)) # +0001234 

Non-numeric strings are treated the same way.

s = 'abcd' print(s.zfill(8)) # 0000abcd 

Because zfill() is a method of str , it cannot be called from objects of other types, such as int . To pad an integer with zeros, first convert it to a string using str() , then call zfill() .

i = 1234 print(type(i)) # # print(i.zfill(8)) # AttributeError: 'int' object has no attribute 'zfill' print(str(i).zfill(8)) # 00001234 

Right-justified, centered, left-justified: rjust() , center() , ljust()

If you want to center or left-justify in addition to right-justify and zero-fill, use the center() and ljust() methods of str .

For these methods, the first argument is the length of the string to be returned, and the second argument is ‘0’ for zero-padding.

s = '1234' print(s.rjust(8, '0')) # 00001234 print(s.center(8, '0')) # 00123400 print(s.ljust(8, '0')) # 12340000 

Note that a leading sign prefix ( — , + ) is not considered.

s = '-1234' print(s.rjust(8, '0')) # 000-1234 print(s.center(8, '0')) # 0-123400 print(s.ljust(8, '0')) # -1234000 

Since these are also methods of str , to apply them to numbers, convert a number to a string with str() before calling them.

Format: format() , f-strings

The built-in format() function and the format() method of str provide various formatting options, including zero-padding.

Examples of right-justified and zero-filled with the format() method of str are shown here. For other examples and detailed usage, see the following articles.

For strings, use 0>[STRING_LENGTH] as the format string. A leading sign prefix ( + , — ) is not considered.

s = '1234' print('Zero Padding: 8>'.format(s)) # Zero Padding: 00001234 s = '-1234' print('Zero Padding: 8>'.format(s)) # Zero Padding: 000-1234 

Since a leading sign prefix is considered for numbers as described later, if you want to consider the sign, use int() to convert a string to an integer. In that case, use 0[STRING_LENGTH] .

s = '-1234' print('Zero Padding: '.format(int(s))) # Zero Padding: -0001234 

For numbers, use 0[STRING_LENGTH] . A leading sign prefix is considered. You can also do various operations, e.g., convert to hexadecimal and zero-padding.

i = 255 print('Zero Padding: '.format(i)) # Zero Padding: 00000255 print('Zero Padding: '.format(i)) # Zero Padding: 000000ff i = -1234 print('Zero Padding: '.format(i)) # Zero Padding: -0001234 

In Python 3.6 or later, you can also use f-strings for a more concise representation.

print(f'Zero Padding: i:08>') # Zero Padding: -0001234 

The % operator for strings

You can use the % operator with a string to achieve formatted output.

Note that f-strings and format() are recommended in the official documentation.

Note: The formatting operations described here exhibit a variety of quirks that lead to a number of common errors (such as failing to display tuples and dictionaries correctly). Using the newer formatted string literals, the str.format() interface, or template strings may help avoid these errors. Each of these alternatives provides their own trade-offs and benefits of simplicity, flexibility, and/or extensibility. Built-in Types — printf-style String Formatting — Python 3.11.3 documentation

For integers, use %0[STRING_LENGTH]d

i = 1234 print('Zero Padding: %08d' % i) # Zero Padding: 00001234 i = -1234 print('Zero Padding: %08d' % i) # Zero Padding: -0001234 

For strings, it is filled with spaces. If you want to fill it with zeros, convert it to an integer with int() .

s = '1234' print('Zero Padding: %08s' % s) # Zero Padding: 1234 print('Zero Padding: %08d' % int(s)) # Zero Padding: 00001234 

Источник

How to pad zeros to a String in Python

This article shows how to pad a numeric string with zeroes to the left such that the string has a specific length.

It also shows how numbers can be converted to a formatted String with leading zeros.

Use str.zfill(width) ¶

zfill is the best method to pad zeros from the left side as it can also handle a leading ‘+’ or ‘-‘ sign.

It returns a copy of the string left filled with ‘0’ digits to make a string of length width. A leading sign prefix (‘+’/’-‘) is handled by inserting the padding after the sign character rather than before. The original string is returned if width is less than or equal to len(s).

Use str.rjust(width[, fillbyte]) ¶

If you want to insert an arbitrary character on the left side, use rjust. It returns a copy of the object right justified in a sequence of length width. The default filling character is a space. However, this does not handle a sign prefix.

Numbers can be padded with string formatting¶

Converted a number to a formatted string with leading zeros by using string formatting:

FREE VS Code / PyCharm Extensions I Use

✅ Write cleaner code with Sourcery, instant refactoring suggestions: Link*

PySaaS: The Pure Python SaaS Starter Kit

🚀 Build a software business faster with pure Python: Link*

* These are affiliate link. By clicking on it you will not have any additional costs. Instead, you will support my project. Thank you! 🙏

Источник

Python Pad String With Zeros

How to pad string with zeros in Python? Adding some characters/values to the string is known as Padding. In Python, zfill() and rjust() methods are used to pad zeros at the beginning of the string and ljust() is used to pad zeros at the end of the string. With the ljust() and rjust() you can fill in any characters but in this article, I will use them to fill in zeros.

Alternatively, by using f-strings, we can pad zeros to the string in two ways. Using ‘>’, we can pad zeros at left, and using ‘

1. Quick Examples of padding zeros to string

Following are quick examples of how to pad or fill zeros to the string to get a specific length of a string.

 # Quick Examples # Consider the string that include 16 characters. string1 = "sparkby examples" print("String: ",string1) # Using zfill() print(string1.zfill(30)) # Pad left using rjudt() print(string1.rjust(30, '0')) # Pad right using ljust() print(string1.ljust(30, '0')) # Pad left using f-strings print(f"30>") # Pad right using f-strings print(f"30>'".format(string1)) # Pad right using format() print(''.format(string1)) 

2. Pad Zeros to String using rjust()

The rjust() method is Python’s str class that is used to pad zeros on the left of the python string (string is aligned to the right). This method takes two arguments: the minimum width of the string as value, and an optional padding character (which is a space by default).

This method returns a new string with the specified width after padding the fill character to the original string. For example, If your string length is 6, and the value specified inside rfill() is 10, then 4 zeros are padded to the left of the string, so the final length of the string is 10.

2.1 rjust() Syntax

 # Syntax of rjust() string1.rjust(value, '0') 

2.2 rjust() Parameters

  1. value is the first parameter that specify the total length of the string after padding zeros.
  2. Second parameter takes the element that has to be padded to the string. In our case, it is ‘0’.

2.3 Pad Zeros to the Left of the String

Let’s create a string and pad the zeros at the start (left of the string).

 # Consider the string that include 6 characters. string1 = "PYTHON" print("String: ",string1) # Pad 4 zeros to the left to get string length 10 print(string1.rjust(10, '0')) # Output: # String: PYTHON # 0000PYTHON 

3. Pad Zeros to String using ljust()

The ljust() method is also Python’s str class that is used to pad zeros on the right of the python string (string is aligned to the left). This method also takes two arguments: the minimum width of the string as value, and an optional padding character (which is a space by default).

If your string length is 7, and the value specified inside rfill() is 10, then 3 zeros are padded to the right of the string, so the final length of the string is 10.

3.1 ljust() Syntax

Following is the syntax of the ljust()

 # Syntax of ljust() string1.ljust(value, '0') 

3.2 ljust() Parameters

  1. value is the first parameter that specifies the total length of the string after padding zeros.
  2. Second parameter takes the element that has to be padded to the string. In our case it is ‘0’.

3.3 Example

By using ljust() method, let’s pad zeros at the end of the string.

 # Pad 4 zeros to the right to get string length 10 print(string1.ljust(10, '0')) # Output: # PYTHON0000 

4. Pad Zeros to String using zfill()

The zfill() is used to fill the string with zeros at the start of the string (left of the string). It takes the value as a parameter that specifies the total length of the string along with zeros. By default, zfill() treats the string as a numeric value and removes any leading plus or minus sign. If you want to preserve the sign, you can pass the sign parameter as ‘+’ or ‘-‘

If you have a string length of 6 and specify 10 as the length, zfill() returns a string with the length 10 that includes 4 zeroes on the left.

4.1 zfill() Syntax

Let’s look at the syntax of zfill()

 # Here, string1 is the input string. string1.zfill(value) 

4.2 Example

Here, let’s use the zfill() to fill the zeros on the left of the string.

 # Use zfill() to pad zeros print(string1.zfill(10)) # Output: # 0000PYTHON 

5. Pad Zeros to String using f-strings

  1. If we specify element > value, zeros are padded at the start of the string (left padding).
  2. If we specify element < value, zeros are padded at the end of the string (right padding).

The value specified will be equal to the length of the string after padding.

5.1 f-strings Syntax

Let’s look at the syntax of f-strings with left and right paddings.

 # Syntax of f-strings # Specify element as 0 to pad zeros. # Syntax of Left padding f" value>" # Syntax of Right padding f"" 

5.2 Example

Create a string with 6 characters and pad zeros by specifying different values at Left and Right using f-strings.

 # Consider the string that include 7 characters. string1 = "PYTHON" print("String: ",string1) # Pad left print(f"10>") # Pad right print(f"") # Output: # String: PYTHON # 0000PYTHON # PYTHON0000 
  • First example – 4 zeros are Left padded by specifying the value as 10.
  • Second example – 4 zeros are Right padded by specifying the value as 10.
  • In both outputs, the length of the final string is 10, as the value is 10.

6. Pad Zeros to String using format()

Finally, format() in python is used to display the strings in the desired formats similar to f-strings. It can be used to pad zeros at Left and Right with > and < operators. But we need to specify this inside <>.

The value specified will be equal to the length of the string after padding.

6.1 format() Syntax

Let’s look at the syntax of format() with Left and Right Paddings.

 # Syntax of format() # Specify element as 0 to pad zeros. # Syntax of Left padding ' value>'.format(string1) # Syntax of Right padding ''.format(string1) 

6.2 Example

Let’s use the ‘<>’ .format() to pad or fill zeros on the left and right of the string in python.

 # Consider the string that include 6 characters. string1 = "PYTHON" print("String: ",string1) # Pad left print('10>'.format(string1)) # Pad right print(''.format(string1)) # Output: # String: PYTHON # 0000PYTHON # PYTHON0000 

7. Conclusion

In this article, you have learned zfill() and rjust() is used to fill or pad the zeros on the left of the string, and ljust() is used to fill on the right of the string in Python. Alternatively, you can also use f-string and format() to fill the zeros on the string to get the desired width of the stirng.

You may also like reading:

Источник

Читайте также:  Astra linux python pip
Оцените статью