Remove the leading zero before a number in python [duplicate]
·
Answer a question
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.
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]
更多推荐

所有评论(0)