regex help

Cameron Simpson cs at zip.com.au
Fri Mar 13 18:37:51 EDT 2015


On 13Mar2015 12:05, Larry Martell <larry.martell at gmail.com> wrote:
>I need to remove all trailing zeros to the right of the decimal point,
>but leave one zero if it's whole number. For example, if I have this:
>
>14S,5.0000000000000000,4.56862745000000,3.7272727272727271,3.3947368421052630,5.7307692307692308,5.7547169811320753,4.9423076923076925,5.7884615384615383,5.137254901960000
>
>I want to end up with:
>
>14S,5.0,4.56862745,3.7272727272727271,3.394736842105263,5.7307692307692308,5.7547169811320753,4.9423076923076925,5.7884615384615383,5.13725490196
>
>I have a regex to remove the zeros:
>
>'0+[,$]', ''
>
>But I can't figure out how to get the 5.0000000000000000 to be 5.0.
>I've been messing with the negative lookbehind, but I haven't found
>one that works for this.

Leaving aside the suggested non-greedy match, you can rephrase this: strip 
trailing zeroes _after_ the first decimal digit. Then you can consider a number 
to be:

  digits
  point
  any digit
  other digits to be right-zero stripped

so:

  (\d+\.\d)(\d*[1-9])?0*\b

and keep .group(1) and .group(2) from the match.

Another way of considering the problem.

Or you could two step it. Strip all trailing zeroes. If the result ends in a 
dot, add a single zero.

Cheers,
Cameron Simpson <cs at zip.com.au>

C'mon. Take the plunge. By the time you go through rehab the first time,
you'll be surrounded by the most interesting people, and if it takes years
off of your life, don't sweat it. They'll be the last ones anyway.
        - Vinnie Jordan, alt.peeves



More information about the Python-list mailing list