Skip to main content

How to remove trailing zeros from a string in Python

How to remove trailing zeros from a string in Python.

Here is a step-by-step tutorial on how to remove trailing zeros from a string in Python:

Step 1: Input the string

To begin, you need to input the string that contains the trailing zeros you want to remove. This can be done by assigning the string to a variable. For example, let's say our string is "10.5000".

string = "10.5000"

Step 2: Use the rstrip() method

The rstrip() method in Python removes characters from the right end of a string. We can use this method to remove the trailing zeros from our string.

string = string.rstrip('0')

In this example, we are removing all instances of the character '0' from the right end of the string.

Step 3: Check if the string is now empty

After using the rstrip() method, we should check if the string is empty. If it is empty, it means that all the characters in the string were trailing zeros. In such cases, we can assign a default value or handle it as needed.

if string == "":
string = "0"

In this example, we assign the default value of "0" to the string if it becomes empty.

Step 4: Print the modified string

Finally, we can print the modified string to verify that the trailing zeros have been successfully removed.

print(string)

Here is the complete code:

string = "10.5000"
string = string.rstrip('0')

if string == "":
string = "0"

print(string)

This code will output:

10.5

You can try this code with different input strings to remove trailing zeros and obtain the desired output.