Home > Blockchain >  Regex to remove leading zero except for first
Regex to remove leading zero except for first

Time:11-23

I have the following cases where I'd like to remove the leading zeros

0 -> 0
0.1 -> 0.1
-0.1 -> -0.1
00.01 -> 0.01
001 -> 1

So whenever there are multiple zeros before the decimal or number, then we remove them. If the zero is by itself, we keep it. I have the following regex:

r'^[0]*'

but this removes all leading zeros. How can I fix this so that it does what I want it to do?

CodePudding user response:

You can use the Decimal class to convert the string to a number and back:

>>> from decimal import Decimal
>>> str(Decimal("0.01"))
'0.01'
>>> str(Decimal("000.01"))
'0.01'
>>> str(Decimal("-00.01"))
'-0.01'
>>> str(Decimal("1"))
'1'

CodePudding user response:

If want to use a regexp then try something like this to replace a sequence of 0's in front of another number.

import re

for n in ['0', '0.1', '-0.1', '00.01', '001']:
     x = re.sub(r'^0 ([0-9])', r'\1', n)
     print(f"{n:10s} {x}")

Output:

0          0
0.1        0.1
-0.1       -0.1
00.01      0.01
001        1
  • Related