best way to remove leading zeros from a tuple like string

Ben Bacarisse ben.usenet at bsb.me.uk
Sun May 20 17:19:10 EDT 2018


bruceg113355 at gmail.com writes:

> Lets say I have the following tuple like string.
>   (128, 020, 008, 255)
>
> What is the best way to to remove leading zeroes and end up with the following.
>   (128, 20, 8, 255)        -- I do not care about spaces

You could use a regexp:

  import re
  ...
  re.sub(r"(?<![0-9])0+(?=[0-9])", "", "(128, 020, 008, 255)")

I post this because I think it works (interesting corner cases are 10005
and 000), but I don't think, having done it, that it's the right way to
go.  It's a little too mysterious and fragile.

This may be better:

  re.sub(r"[0-9]+", lambda m: str(int(m.group(0))), "(128, 020, 008, 255)")

Obviously, name the function if you prefer (or if you use this in
several places) and compile the pattern if you do a lot of these matches.

-- 
Ben.



More information about the Python-list mailing list