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

best way to remove leading zeros from a tuple like string


bruceg113355 at gmail.com wrote:

> 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
> 
> This is the solution I came up with
>     s = "(128, 020, 008, 255)"
>     v = s.replace ("(", "")
>     v = v.replace (")", "")
>     vv = ",".join([str(int(i)) for i in v.split(",")])
>     final = "(" + vv + ")"

Two more:

>>> s = "(0000128, 020, 008, 255, -1203,01,-000, -0123)"

>>> str(tuple(map(int, s[1:-1].split(","))))
'(128, 20, 8, 255, -1203, 1, 0, -123)'

>>> re.sub(r"\b0+\B", "", s)
'(128, 20, 8, 255, -1203,1,-0, -123)'