osdir.com

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

best way to remove leading zeros from a tuple like string


On Sunday, May 20, 2018 at 6:56:05 PM UTC-4, Ben Bacarisse wrote:
> "Michael F. Stemper" <michael.stemper at gmail.com> writes:
> 
> > On 2018-05-20 16:19, Ben Bacarisse wrote:
> >> 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), 
> >
> > Seeing this makes me realize that mine will eliminate any numbers that
> > are all leading zero, including '0'. Also, forms like '-0042' will be
> > left unchanged.
> 
> I realised after posting the negatives won't work.  Not, I suspect, an
> issue for the OP but -0042 can certainly be said to have "leading
> zeros".
> 
> > Maybe splitting it into integer forms and sending each through
> > str( int( ) ) would be the safest.
> 
> Yup.  I gave a version of that method too which handles negative numbers
> by accident (by leaving the - in place!).  A better version would be
> 
>   re.sub(r"-?[0-9]+", lambda m: str(int(m.group(0))), s)
> 
> <snip>
> -- 
> Ben.



Looking over the responses, I modified my original code as follows:

>>> s = "(0000128, 020, 008, 255, -1203,01,-000, -0123)" 
>>> ",".join([str(int(i)) for i in s[1:-1].split(",")])
'128,20,8,255,-1203,1,0,-123'


If I decide I need the parentheses, this works.

>>> "(" + ",".join([str(int(i)) for i in s[1:-1].split(",")]) + ")"
'(128,20,8,255,-1203,1,0,-123)'

Thanks,
Bruce