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
  • 52,758
  • 11
  • 94
  • 99
user2896120
  • 2,935
  • 4
  • 35
  • 77

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
  • 52,758
  • 11
  • 94
  • 99
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
0

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

^0+\B

See demo at regex101

bobble bubble
  • 11,625
  • 2
  • 24
  • 38