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
Add trailing Zeros to a Python string
When processing strings in Python, you may need to add trailing zeros for formatting purposes such as padding numbers or creating fixed-width strings. Python provides several methods to accomplish this task efficiently.
Using ljust() Method
The ljust() method returns a string left-justified within a specified width, padding with a given character. Combined with len(), it allows dynamic zero padding ?
Example
# Add trailing zeros to a Python string
# initializing string
text = 'Jan-'
print("The given input: " + text)
# Number of zeros required
n = 3
# Using ljust() to add trailing zeros
output = text.ljust(n + len(text), '0')
print("Adding trailing zeros to the string: " + output)
The output of the above code is ?
The given input: Jan- Adding trailing zeros to the string: Jan-000
Using format() Method
The format() method provides flexible string formatting using placeholders. The < symbol indicates left alignment, while the total width and fill character can be specified ?
Example
text = 'Spring:'
print("The given input: " + text)
# Using format() to add trailing zeros
# {:<09} means left-align, pad with '0', total width 9
z = '{:0<9}'
output = z.format(text)
print("Adding trailing zeros to the string: " + output)
The output of the above code is ?
The given input: Spring: Adding trailing zeros to the string: Spring:00
Using f-strings (Python 3.6+)
F-strings provide a modern and readable approach to string formatting with the same padding capabilities ?
Example
text = 'Data-'
print("The given input: " + text)
# Using f-string to add trailing zeros
width = 10
output = f'{text:0<{width}}'
print("Adding trailing zeros to the string: " + output)
The output of the above code is ?
The given input: Data- Adding trailing zeros to the string: Data-00000
Comparison
| Method | Flexibility | Readability | Python Version |
|---|---|---|---|
ljust() |
Good | Good | All versions |
format() |
Excellent | Very good | 2.7+ |
| f-strings | Excellent | Excellent | 3.6+ |
Conclusion
Use ljust() for simple padding needs, format() for complex formatting, and f-strings for modern, readable code. All methods effectively add trailing zeros to strings based on your specific requirements.
