Pad String With Zeros in Python Delft Stack
Pad String With Zeros in Python Delft Stack
delftstack.com
4 minutes
1.
2. HowTo
3. Python How-To's
1 of 5 11/10/22, 15:54
Pad String With Zeros in Python | Delft Stack about:reader?url=https%3A%2F%2Fwww.delftstack.com%...
For example,
pythonCopy
A = '007'
B = '1.000'
C = '4876'
print(A.zfill(5))
print(B.zfill(6))
print(C.zfill(3))
Output:
textCopy
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.
2 of 5 11/10/22, 15:54
Pad String With Zeros in Python | Delft Stack about:reader?url=https%3A%2F%2Fwww.delftstack.com%...
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.
For example,
pythonCopy
A = 'Hello'
B = 'World'
print(A.rjust(7,"0"))
print(B.ljust(8,"0"))
Output:
textCopy
00Hello
World000
3 of 5 11/10/22, 15:54
Pad String With Zeros in Python | Delft Stack about:reader?url=https%3A%2F%2Fwww.delftstack.com%...
For example,
pythonCopy
A = 'Hello'
B = 'CR7'
print('{:0>8}'.format(A))
print('{:0>5}'.format(B))
Output:
textCopy
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.
For example,
4 of 5 11/10/22, 15:54
Pad String With Zeros in Python | Delft Stack about:reader?url=https%3A%2F%2Fwww.delftstack.com%...
pythonCopy
A = 'Hello'
B = 'CR7'
print(f'{A:0>8}')
print(f'{B:0>5}')
Output:
textCopy
000Hello
00CR7
5 of 5 11/10/22, 15:54