Python - How To Pad String With Zeros in Python

ID : 52

viewed : 122

Tags : PythonPython String

vote vote

92

To make a string of the desired length, we add or pad a character at the beginning or the end of the string until it is of the required length.

In this tutorial, we will discuss how to pad a string with zeros in Python.

Use the zfill() String Method to Pad a String With Zeros in Python

The zfill() method in Python takes a number specifying the desired length of the string as a parameter and adds zeros to the left of the string until it is of the desired length. If the number passed in as the parameter is smaller than the length of the original string, then there is no change.

For example,

A = '007' B = '1.000' C = '4876' print(A.zfill(5)) print(B.zfill(6)) print(C.zfill(3)) 

Output:

00007 01.000 4876 

In the above example, two zeros were added at the beginning of string A to make it of length five. Similarly, one zero was added at the beginning of string B to make it of length six. No changes were made in string C since the number passed in as a parameter in the zfill() method is smaller than the length of the original string.

Use the rjust() or ljust() String Method to Pad a String With Zeros in Python

The rjust() or ljust() method in Python takes a number specifying the desired length of the string as the required parameter and a character as an optional parameter.

The rjust() method adds the optional character to the left of the string until the string is of the desired length. Similarly, the ljust() method adds the optional character to the right of the string until the string is of the desired length.

If the character is not specified, the default is space " ".

For example,

A = 'Hello' B = 'World' print(A.rjust(7,"0")) print(B.ljust(8,"0")) 

Output:

00Hello World000 

Two zeros were added at the beginning of string A to make it of length seven using the rjust() method. Similarly, three zeros were added at the end of string B to make it of length eight using the ljust() method.

Use the format() to Pad a String With Zeros in Python

The format() method in Python can format strings to display them in our desired format based on some pattern. We can use it to add zeros to the left of the string until the string is of the desired length. This method can only be used for Python 2 to Python 3.5.

For example,

A = 'Hello' B = 'CR7' print('{:0>8}'.format(A)) print('{:0>5}'.format(B)) 

Output:

000Hello 00CR7 

The {:0>8} is the pattern used to pad the string A and increase its size to 8. Similarly, {:0>5} pads the string B to the desired length.

Use the F-Strings to Pad a String With Zeros in Python

The f-strings is an addition in recent versions of Python and provides quick formatting of strings. We can use it to pad a string with zeros also.

This is similar to the previously discussed method.

For example,

A = 'Hello' B = 'CR7' print(f'{A:0>8}') print(f'{B:0>5}') 

Output:

000Hello 00CR7 

  • Related HOW TO?