Python Remove Leading and Trailing Zeros

Python Remove Leading and Trailing Zeros

Quiet a few times while working on certain things you can find the need to remove leading and trailing zeros or any other characters.

Python provides built-in type which can be used to remove leading and trailing zeroes or characters. The Python built-in type we are talking about here is str.strip([chars]).

Python Remove Leading and Trailing Zeros

str.strip([chars])

Return a copy of the string with the leading and trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped

To make it simple str.strip([chars]), removes the leading and trailing characters provided as chars. If there isn’t any value supplied it will remove the whitespaces

Python Remove Leading and Trailing Zeros

Let’s take some example.

I will use the string value as 000806000 and assign it to a variable a.

>>> a='000806000'
>>> a
'000806000'

Now, let’s remove the leading and trailing zeros using strip()

>>> a.strip('0')
'806'

You see in the above example the leading and trailing 0 are removed.

I will provide another example where no chars is passed to strip().

Let’s get another variable with some whitespaces.

>>> b='    Gagan   '
>>> b
'    Gagan   '

Now let’s see what happens if we do not provide any chars to strip().

>>> b.strip()
'Gagan'

However, this does not limit here. The build-in type str.strip([chars]) does have the ability to remove just the leading characters or just the trailing characters as well.

Python Remove Leading and Trailing Zeros – Remove Leading Characters

We can use str.lstrip([chars]) to remove just the leading characters (in this case zeros) from a string.

Let’s consider the example of the variable a above. Using str.lstrip([chars]) we will remove the leading zeros.

>>> a
'000806000'
>>> a.lstrip('0')
'806000'

Python Remove Leading and Trailing Zeros – Remove Trailing Characters

Similarly we can use str.rstrip([chars]) to remove just the trailing characters from a string.

Continuing the same example for variable a, let’s remove the trailing zeros.

>>> a.rstrip('0')
'000806'

Python Remove Leading and Trailing Zeros

No Comments

Post a Comment

Time limit is exhausted. Please reload CAPTCHA.