Python regex how to remove all zeo from beginning?

Question:

I have lot of string somethings like this "01568460144" ,"0005855048560"

I want to remove all zero from beginning. I tried this which only removing one zeo from beginning but I also have others string those have multiple zeo at the beginning.

re.sub(r'0','',number)

so my expected result will be for "0005855048560" this type of string "5855048560"

Asked By: boyenec

||

Answers:

>>> v = '0001111110'
>>> 
>>> str(int(v))
'1111110'
>>> 
>>> str(int('0005855048560'))
'5855048560'
Answered By: islam abdelmoumen

If the goal is to remove all leading zeroes from a string, skip the regex, and just call .lstrip('0') on the string. The *strip family of functions are a little weird when the argument isn’t a single character, but for the purposes of stripping leading/trailing copies of a single character, they’re perfect:

>>> s = '000123'
>>> s = s.lstrip('0')
>>> s
'123'
Answered By: ShadowRanger

If the string should contain only digits, you can use either isnumeric() or use re.sub and match only digits:

import re

strings = [
    "01568460144",
    "0005855048560",
    "00test",
    "00000",
    "0"
]

for s1 in strings:
    if s1.isnumeric():
        print(f"'{s1.lstrip('0')}'")
    else:
        print(f"'{s1}'")

print("----------------------------")

for s2 in strings:
    res = re.sub(r"^0+(d*)$", r"1", s2)
    print(f"'{res}'")

Output

'1568460144'
'5855048560'
'00test'
''
''
----------------------------
'1568460144'
'5855048560'
'00test'
''
''
Answered By: The fourth bird
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.