To add trailing zeros to a string in Python, the easiest way is with the + operator.
string = "hello"
print(string + "000")
#Output:
hello000
You can also use the Python string ljust() function to add trailing zeros to a string.
string = "hello"
print(string.ljust(8,"0"))
#Output:
hello000
One last way is with the format() function.
string = "hello"
print("{:<08}".format(string))
#Output:
hello000
When working with strings, the ability to easily modify the values of the variables easily is valuable.
One such situation is when you have a string and want to add trailing zeros to the string.
To add trailing zeros to a string in Python, the easiest way is with +. In this case, you aren't worried about length, you know how many zeros you want, and you just want to add trailing zeros to your string.
Below is an example showing you how to add trailing zeros with string concatenation in Python.
string = "hello"
print(string + "000")
#Output:
hello000
Using ljust() Function to Add Trailing Zeros to String in Python
Another way you can add trailing zeros to a string in Python is with the ljust() function.
ljust() takes two parameters. The first is the length of the new string that ljust() will create and the second parameter is the character to add to the right of the string.
Adding trailing zeros with ljust() is more useful if you want to get a specific length for your new string and don't always know the length of the string variable you are using.
Below is an example of adding trailing zeros to a string with ljust() in Python.
string = "hello"
print(string.ljust(8,"0"))
#Output:
hello000
Using format() Function to Add Trailing Zeros to String in Python
One last way you can add trailing zeros to a string in Python is with the Python string format() function.
The correct format to use has the form "{:<0N}" where N is the length of the new string you want to create, '0' is for zero, and '<' is for trailing. Using this method is similar to the method with ljust() because here you could easily add trailing zeros to a collection of strings to make all of the strings have the same length.
Below is the example showing you how to use format() in Python to add trailing zeros to a string.
string = "hello"
print("{:<08}".format(string))
#Output:
hello000
Hopefully this article has been useful for you to learn how to add trailing zeros to a string in Python.