12

I have a string which correspond to a number but with several leading zeros before it. What I want to do is to remove the zeros that are before the number but not in the number. For example "00000001" should be 1 and "00000010" should be 10. I wrote code that remove zeros but also the tailing one:

segment = my_str.strip("0")

That code removes all zeros. How can I only remove the leading zeros before the number.

Jose Ramon
  • 5,572
  • 25
  • 76
  • 152

2 Answers2

34

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]
NPE
  • 486,780
  • 108
  • 951
  • 1,012
5

just use the int() function, it will change the string into an integer and remove the zeros

my_str = '00000010'    
my_int = int(my_str)    
print(my_int)

output:

10
alper
  • 2,919
  • 9
  • 53
  • 102
Cory L
  • 273
  • 1
  • 12
  • Note that if you need to keep the value a string for whatever reason, you can do the opposite conversion to get it back: `str(int('00000010'))` – Sam Krygsheld Nov 02 '20 at 22:28