Regex to remove leading zero except for first

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?

3 answers

  • answered 2021-11-23 02:03 Selcuk

    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'
    

  • answered 2021-11-23 03:00 asiloisad

    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
    

  • answered 2021-11-23 11:57 bobble bubble

    Or this weird one:

    ^0+\B
    

    See demo at regex101 - \B matches a non word boundary.

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum