Remove Leading And Trailing Zeros From A String In Python

Remove Leading And Trailing Zeros From A String In Python

Following this article below, I will share with you how to remove leading and trailing Zeros from a string in Python in the simplest. Let’s go into detail now.

Remove leading and trailing Zeros from a string in Python

Using rstrip() and lstrip() to remove leading and trailing Zeros

Here, we use the rstrip() method in the lstrip() method to remove a character leading and trailing in a string. This is the easiest way to remove it. Follow the code example below to better understand.

Syntax:

str.lstrip(character1)
str.rstrip(character2)

Parameters:

  • character1: characters you want to remove as leading.
  • character2: characters you want to remove as trailing.

Returns: a new string is removed.

So, I will remove leading and trailing zeros for you to understand. Look at the following example:

Code example:

# Initialize a string you want to remove leading zeros
strleft = "0001learnshare1"

# Remove leading zeros
newstr1 = strleft.lstrip("0")

# Print new string
print("New string remove leading zeros:",newstr1)

# Initialize a string you want to remove trailing zeros
strleft = "1learnshare00000"

# Remove leading zeros
newstr2 = strleft.rstrip("0")

# Print new string
print("New string remove trailing zeros:",newstr2)

Output:

New string remove leading zeros: 1learnshare1
New string remove trailing zeros: 1learnshare

Now we will contribute rstrip() and lstrip() methods. We will have a new string remove leading and trailing zeros from a string. See code example.

Code example:

# Initialize a string you want to remove leading zeros
strleft = "000Learn Share IT00000"

# Remove leading and trailing zeros
newstr1 = strleft.lstrip("0")
newstr2 = newstr1.rstrip("0")

# Print new string
print("New string remove leading and trailing zeros:",newstr2)

Output:

New string remove leading and trailing zeros: Learn Share IT

Using while-Loop and slicing

We can use while-loop and slicing to remove leading and trailing Zeros from a string.

Here, we will use a while-loop to find the character you want to remove and slice to return a new string of our choice.

Code example:

# Initialize a variable store string
str = "0000Learn Share IT12300000"

# Remove leading zeros
while str[0] == "0":
    str = str[1:]

# Remove trailing zeros
while str[-1] == "0":
    str = str[:-1]

# Print new string
print("New string is:",str)

Output:

New string is: Learn Share IT123

Summary

So we’re done learning the easiest methods about how to remove leading and trailing Zeros from a string in Python. I hope you find the method that works best for you. If you have any questions, please leave a comment below. Have a good luck!

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *