Python: Add leading zeroes to a string
Add Leading Zeroes
Write a Python program to add leading zeroes to a string.
Pictorial Presentation:
Sample Solution-1:
Python Code:
# Define the original string 'str1'.
str1 = '122.22'
print("Original String: ", str1)
# Print a message to indicate the purpose of the code.
print("\nAdded trailing zeros:")
# Use the 'ljust' method to add trailing zeros to 'str1' to make its total width 8.
str1 = str1.ljust(8, '0')
print(str1)
# Repeat the process to make the total width 10.
str1 = str1.ljust(10, '0')
print(str1)
# Print a message to indicate the addition of leading zeros.
print("\nAdded leading zeros:")
# Reset 'str1' to the original value.
str1 = '122.22'
# Use the 'rjust' method to add leading zeros to 'str1' to make its total width 8.
str1 = str1.rjust(8, '0')
print(str1)
# Repeat the process to make the total width 10.
str1 = str1.rjust(10, '0')
print(str1)
Sample Output:
Original String: 122.22 Added trailing zeros: 122.2200 122.220000 Added leading zeros: 00122.22 0000122.22
Sample Solution-2:
Python Code:
# Define the original string 'str1'.
str1 = '122.22'
print("Original String: ", str1)
# Print a message to indicate the purpose of the code.
print("\nAdded trailing zeros:")
# Define a format text with left alignment and total width of 8.
f_text = '{:<08}'
# Use the 'format' method to add trailing zeros to 'str1' according to the format text.
str1 = f_text.format(str1)
print(str1)
# Define a format text with left alignment and total width of 10.
f_text = '{:<010}'
# Repeat the process to make the total width 10.
str1 = f_text.format(str1)
print(str1)
# Print a message to indicate the addition of leading zeros.
print("\nAdded leading zeros:")
# Reset 'str1' to the original value.
str1 = '122.22'
# Define a format text with right alignment and total width of 8.
f_text = '{:>08}'
# Use the 'format' method to add leading zeros to 'str1' according to the format text.
str1 = f_text.format(str1)
print(str1)
# Define a format text with right alignment and total width of 10.
f_text = '{:>010}'
# Repeat the process to make the total width 10.
str1 = f_text.format(str1)
print(str1)
Sample Output:
Original String: 122.22 Added trailing zeros: 122.2200 122.220000 Added leading zeros: 00122.22 0000122.22
Python Code Editor:
Previous: Write a Python program to check if lowercase letters exist in a string.
Next: Write a Python program to use double quotes to display strings.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics