How to Remove Leading and Trailing Zeros in a String? Python

How to remove leading and trailing zeros in a string? Python

What about a basic

your_string.strip("0")

to remove both trailing and leading zeros ? If you're only interested in removing trailing zeros, use .rstrip instead (and .lstrip for only the leading ones).

More info in the doc.

You could use some list comprehension to get the sequences you want like so:

trailing_removed = [s.rstrip("0") for s in listOfNum]
leading_removed = [s.lstrip("0") for s in listOfNum]
both_removed = [s.strip("0") for s in listOfNum]

Remove the leading zero before a number in python

Use lstrip:

>>> '00000010'.lstrip('0')
'10'

(strip removes both leading and trailing zeros.)

This messes up '0' (turning it into an empty string). There are several ways to fix this:

#1:

>>> re.sub(r'0+(.+)', r'\1', '000010')
'10'
>>> re.sub(r'0+(.+)', r'\1', '0')
'0'

#2:

>>> str(int('0000010'))
'10'

#3:

>>> s = '000010'
>>> s[:-1].lstrip('0') + s[-1]

Remove trailing .0 from strings of entire DataFrame

Let's try DataFrame.replace:

import pandas as pd

df = pd.DataFrame({
'a': ['20', '34.0'],
'b': ['39.0', '.016.0'],
'c': ['17-50', '001-6784532']
})

df = df.replace(r'\.0$', '', regex=True)

print(df)

Optional DataFrame.astype if the columns are not already str:

df = df.astype(str).replace(r'\.0$', '', regex=True)

Before:

      a       b            c
0 20 39.0 17-50
1 34.0 .016.0 001-6784532

After:

    a     b            c
0 20 39 17-50
1 34 .016 001-6784532

rtrim/rstrip will not work here as they don't parse regex but rather take a list of characters to remove. For this reason, they will remove all 0 because 0 is in the "list" to remove.

Remove leading zeros from python complex executable string

You could try to come up with a regular expression for numbers with leading zeros and then replace the leading zeros.

import re

def remove_leading_zeros(string):
return re.sub(r'([^\.^\d])0+(\d)', r'\1\2', string)

print(remove_leading_zeros("np.where(x < 02, np.where(x > 01.5025, (0.9), (0.5)), (1))"))

# output: np.where(x < 2, np.where(x > 1.5025, (0.9), (0.5)), (1))

The remove_leading_zeros function basically finds all occurrences of [^\.^\d]0+\d and removes the zeros. [^\.^\d]0+\d translates to not a number nor a dot followed by at least one zero followed by a number. The brackets (, ) in the regex signalize capture groups, which are used to preserve the character before the leading zeros and the number after.


Regarding Csaba Toth's comment:

The problem with 02+03*04 is that there is a zero at the beginning of the string.
One can modify the regex such that it matches also the beginning of the string in the first capture group:

r"(^|[^\.^\d])0+(\d)"

Better way to remove trailing zeros from an integer

Just use str.rstrip():

def remove_zeros(number):
return int(str(number).rstrip('0'))

You could also do it without converting the number to a string, which should be slightly faster:

def remove_zeros(number):
while number % 10 == 0:
number //= 10
return number

Remove trailing zeros from binary result in python

It easy with string formatting functions (see Pranav's comment). But perhaps in this case you want the algorithm to take care of it, and see treating it as a string is cheating.

def dec2bin(value, number_bits):
result = ''
starting = True
while number_bits > 0:
bit_value = 2 ** (number_bits - 1)
if value >= bit_value:
result = result + '1'
value = value - bit_value
starting = False
elif not starting:
result = result + '0'
number_bits = number_bits - 1
print(result)

Remove leading zeros only in case of integers datatype

Converting my comment to answer so that solution is easy to find for future visitors.

You may be able to use:

df['CRITERIA_VALUE'].str.replace(r'^0+(?=[0-9]+$)', '', regex=True)

RegEx Details:

  • ^0+: Match 1+ zeroes at the start.
  • (?=[0-9]+$): Lookahead to assert that we have 1 or more ASCII digits before end position.

RegEx Demo

Pythonic way to strip all 0's from the front of a string

You can do it like this:

s = str(int(s))

Another alternative is:

s = s.lstrip('0') or '0'

Pandas - Remove leading and trailing zeroes from each row

Using np.trim_zeros:

Trim the leading and/or trailing zeros from a 1-D array or sequence.

out = pd.DataFrame([np.trim_zeros(i) for i in df.values], index=df.index)
out.columns = df.columns[:len(out.columns)]

c1 c2 c3 c4 c5 c6 c7
index
1 1 2 3 4.0 5.0 NaN NaN
2 1 2 3 4.0 5.0 NaN NaN
3 1 2 3 NaN NaN NaN NaN
4 1 2 3 4.0 NaN NaN NaN
5 1 2 3 4.0 5.0 6.0 7.0
6 1 0 0 4.0 NaN NaN NaN


Related Topics



Leave a reply



Submit