Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to get a string left padded with zeros in Python?
String padding is commonly needed when formatting numbers, creating fixed-width output, or aligning text. Python provides several built-in methods to left-pad strings with zeros: rjust(), format(), zfill(), and f-string formatting.
Using rjust() Method
The rjust() method right-justifies a string by padding it with a specified character on the left. It takes two parameters: the total width and the fill character (default is space).
Syntax
string.rjust(width, fillchar)
Example
text = "Welcome to Tutorialspoint"
padded = text.rjust(30, '0')
print("Original string:", text)
print("Padded string:", padded)
print("Length:", len(padded))
Original string: Welcome to Tutorialspoint Padded string: 00000Welcome to Tutorialspoint Length: 30
Using format() Method
The format() method uses format specifiers to control padding. Use {:0>width} where 0 is the fill character, > means right-align (left-pad), and width is the total width.
Example
text = "Python"
padded = '{:0>10}'.format(text)
print("Original string:", text)
print("Padded string:", padded)
Original string: Python Padded string: 0000Python
Using zfill() Method
The zfill() method is specifically designed for zero-padding strings. It's the most straightforward approach when you only need to pad with zeros.
Example
text = "123"
padded = text.zfill(8)
print("Original string:", text)
print("Padded string:", padded)
# Works well with numbers
number = "42"
padded_number = number.zfill(5)
print("Padded number:", padded_number)
Original string: 123 Padded string: 00000123 Padded number: 00042
Using f-string Formatting
F-strings (Python 3.6+) provide a modern way to format strings with zero-padding using the same format specifiers as format().
Example
text = "Hello"
width = 12
padded = f'{text:0>{width}}'
print("Original string:", text)
print("Padded string:", padded)
# Dynamic width
for w in [8, 10, 15]:
print(f"Width {w}: {text:0>{w}}")
Original string: Hello Padded string: 0000000Hello Width 8: 000Hello Width 10: 00000Hello Width 15: 0000000000Hello
Comparison
| Method | Best For | Flexibility | Python Version |
|---|---|---|---|
zfill() |
Zero-padding only | Low | All versions |
rjust() |
Any fill character | Medium | All versions |
format() |
Complex formatting | High | Python 2.7+ |
| f-strings | Modern, readable syntax | High | Python 3.6+ |
Conclusion
Use zfill() for simple zero-padding, rjust() for other fill characters, and f-strings for modern, readable formatting. All methods handle edge cases where the string is already longer than the specified width.
