1

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?

Selcuk
  • 57,004
  • 12
  • 102
  • 110
user2896120
  • 3,180
  • 4
  • 40
  • 100

3 Answers3

1

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'
Selcuk
  • 57,004
  • 12
  • 102
  • 110
1

try this regex:

>>> import re
>>> text = '0\n0.1\n-0.1\n00.01\n001'
>>> print(re.sub(r'0+(\d+)(\.\d+)?', r'\1\2', text))
0
0.1
-0.1
0.01
1
asiloisad
  • 41
  • 4
1

An idea with \B which matches a non word boundary.

^0+\B

See demo at regex101

bobble bubble
  • 16,888
  • 3
  • 27
  • 46