To remove trailing zeros from a string in Python, the easiest way is to use the Python string rstrip() function.

str = "12340000"

print(str.rstrip("0"))

#Output:
1234

You can also use a while loop and slicing to remove trailing zeros from a string.

str = "12340000"

while str[0] == "0":
    str[:-1]

print(str)

#Output:
1234

When working with strings, the ability to easily be able to manipulate and change the values of those strings is valuable.

One such case is if you have trailing zeros in a string which represents an ID or a record number and you want to get rid of those zeros.

To remove trailing zeros from a string in Python, the easiest way is to use the Python string rstrip() function.

rstrip(), or “right strip”, removes a given character from the end of a string if they exist. By default, spaces are removed from the end of the string, but you can pass any character.

Below is a simple example showing you how to use rstrip() to remove trailing zeros from a string in Python.

str = "12340000"

print(str.rstrip("0"))

#Output:
1234

Removing Trailing Zeros from String in Python with While Loop and Slicing

Another way you can remove trailing zeros from a string variable in your Python code is with a for loop and string slicing.

The idea here is that you loop until the last character is not a zero. If it is a zero, then you want to remove the last character from the string.

Below is an example of how to use a while loop and slicing to remove the trailing zeros from a string in Python.

str = "12340000"

while str[0] == "0":
    str[:-1]

print(str)

#Output:
1234

Removing Leading Zeros from String in Python with lstrip() Function

If you have leading zeros, instead of trailing zeros, you can use the Python lstrip() function.

lstrip(), or “left strip”, removes a given character from the beginning of a string if they exist. By default, spaces are removed from the beginning of the string, but you can pass any character.

Below is an example of how you can remove leading zeros from a string using lstrip().

str = "00001234"

print(str.lstrip("0"))

#Output:
1234

Removing Both Leading and Trailing Zeros in Python with strip() Function

If you have both leading and trailing zeros, you can use the Python strip() function.

strip() removes a given character from the beginning and end of a string if they exist. By default, spaces are removed from the beginning and end of the string, but you can pass any character.

Below is an example of how you can remove both leading and trailing zeros from a string using strip().

str = "000012340000"

print(str.strip("0"))

#Output:
1234

Hopefully this article has been useful for you to learn how to remove trailing zeros from a string variable in Python.

Categorized in:

Python,

Last Update: March 22, 2024