Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove the leading zero before a number in python [duplicate]

Tags:

python

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.

like image 833
Jose Ramon Avatar asked Dec 06 '18 14:12

Jose Ramon


2 Answers

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]
like image 110
NPE Avatar answered Oct 17 '22 06:10

NPE


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
like image 36
Cory L Avatar answered Oct 17 '22 06:10

Cory L