Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

string

Python strings have a method called zfill that allows to pad a numeric string with zeros to the left.

In : str(190).zfill(8)
Out: '00000190'

How can I make the pad to be on the right ?

like image 586
yucer Avatar asked Dec 06 '16 16:12

yucer


People also ask

How do I add a zero padding in Python?

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.

How do you pad on the right of a string in Python?

Python string method rjust() returns the string right justified in a string of length width. Padding is done using the specified fillchar (default is a space).

How do you pad an integer with zeros on the left in Python?

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.

How do you pad a number with leading zeros?

To pad an integer with leading zeros to a specific length To display the integer as a decimal value, call its ToString(String) method, and pass the string "Dn" as the value of the format parameter, where n represents the minimum length of the string.


3 Answers

See Format Specification Mini-Language:

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

In [2]: '{:>08d}'.format(190)
Out[2]: '00000190'
like image 66
NarūnasK Avatar answered Oct 26 '22 13:10

NarūnasK


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 (see PEP 3101) and Python 2.6.

[2] reverse twice is an expensive operation.

like image 41
Manoel Vilela Avatar answered Oct 26 '22 11:10

Manoel Vilela


Hint: The string can be inverted twice: before and after using the zfill method:

In : acc = '991000'

In : acc[::-1].zfill(9)[::-1]
Out: '991000000'

Or even more easier:

In : acc.ljust(9, '0')
Out: '991000000'
like image 14
yucer Avatar answered Oct 26 '22 13:10

yucer