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.
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]
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With