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 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.

Maybe splitting it into integer forms and sending each through
str( int( ) ) would be the safest. This partly does the trick, but
packing the results back into a string that resembles a tuple has
been left as a short exercise for the student:

 >>> tuple = '(0128, 020, 000, 008, -0042,255)'
 >>> fields = tuple[1:len(tuple)-1].split(",")
 >>> for field in fields:
...   print( str(int(field)) )
...
128
20
0
8
-42
255
 >>>


-- 
Michael F. Stemper
Why doesn't anybody care about apathy?