close

How to pad a numeric string with zeros to the right in Python?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to pad a numeric string with zeros to the right in Python in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to pad a numeric string with zeros to the right in Python?

  1. How to pad a numeric string with zeros to the right in Python?

    [1] format is not present on old python versions. format specifier was added since Python 3.0 and Python 2.6.

  2. pad a numeric string with zeros to the right in Python

    [1] format is not present on old python versions. format specifier was added since Python 3.0 and Python 2.6.

Method 1

In [1]: '{:<08d}'.format(190)
Out[1]: '19000000'

In [2]: '{:>08d}'.format(190)
Out[2]: '00000190'

Method 2

As maybe a alternative more portable [1] and efficient [2], actually you can just use str.ljust.

In [2]: '190'.ljust(8, '0')
Out[2]: '19000000'

In [3]: str.ljust?
Docstring:
S.ljust(width[, fillchar]) -> str

Return S left-justified in a Unicode string of length width. Padding is
done using the specified fill character (default is a space).
Type:      method_descriptor

[1] format is not present on old python versions. format specifier was added since Python 3.0 and Python 2.6.

[2] reverse twice is an expensive operation.

Conclusion

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read