Open In App

Add trailing Zeros to string-Python

Last Updated : 05 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Add trailing zeros to string in Python involves appending a specific number of zero characters (‘0’) to the end of a given string. This operation is commonly used in formatting, padding, or aligning strings for display or data processing. For example, adding 4 zeros to “GFG” should result in “GFG0000”. Let’s explore some efficient approaches to achieve this in Python.

Using string multiplication

This is the most efficient way to add trailing zeros. By multiplying the string ‘0’ with N, we get a string of N zeros. This result is then concatenated to the original string using +. It’s concise, easy to understand and fast even for large values of N.

Example:

Python
s = 'GFG'

N = 4 # count
res = s + '0' * N # append
print(res) 

Output
GFG0000

Explanation: This first creates a string of N zeros using ‘0’ * N, then joins it with the original string s using +. This gives a new string with zeros added at the end.

Using f-strings

f-Strings offer a modern way to format strings. They support embedding expressions directly inside curly braces {}. Here, ‘0’ * N is evaluated and appended to the string s in one go. This method is especially useful when you have multiple dynamic parts.

Python
s = 'GFG'

N = 4 # count
res = f"{s}{'0' * N}" # append
print(res)

Output
GFG0000

Explanation: This code uses an f-string to combine the original string s with N zeros. Inside the curly braces, ‘0’ * N creates a string of N zeros, which is directly added to the end of s. This results in a new string with zeros added at the end.

Using .ljust()

ljust(width, fillchar) method pads a string to a desired width. In this case, we pad the string s to len(s) + N using ‘0’ as the fill character. This is a great option when you want to pad text for formatting or alignment. It’s clean and avoids manual multiplication or loops.

Python
s = 'GFG'

N = 4 # count
res = s.ljust(len(s) + N, '0') # pad
print(res)

Output
GFG0000

Explanation: ljust() method pad the original string s with zeros on the right. The total length after padding becomes len(s) + N, and ‘0’ is used as the padding character. This adds N zeros at the end of the string.

Using loop

This method manually appends ‘0’ to the string in each iteration. Although easy to understand for beginners, it’s less efficient due to string immutability. Each concatenation creates a new string object, making it slower for large N. Good for educational purposes but not optimal for production use.

Python
s = 'GFG' 
N = 4 # count

for _ in range(N): # loop
    s += '0'

print(s)

Output
GFG0000

Explanation: This code loops to add one ‘0’ to the string s in each iteration and it runs N times, so ‘0’ is added N times to the end of the string, resulting in a new string with N trailing zeros.



Next Article
Practice Tags :

Similar Reads