How to Pad a String with Zeros in Python?

Spread the love

Problem –

You want to pad a string with zeros at the beginning or end in Python until it reaches a desired length.

Solution –

There are various ways to pad a string with zeros in python.

Using Zfill() –

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

In [1]: str1 = "python"

In [2]: str1.zfill(10)
Out[2]: '0000python'

In [3]: str1.zfill(20)
Out[3]: '00000000000000python'

In [4]: str1.zfill(0)
Out[4]: 'python'

Using rjust() and ljust() –

The rjust and ljust method in python takes a number to specify the desired length of the string and a character as an optional parameter. If the character is not provided then by default python adds white space.

In [5]: str1.rjust(10, "0")
Out[5]: '0000python'

In [6]: str1.ljust(10, "0")
Out[6]: 'python0000'

Rating: 1 out of 5.

Leave a Reply