best way to remove leading zeros from a tuple like string

Michael F. Stemper michael.stemper at gmail.com
Sun May 20 17:00:45 EDT 2018


On 2018-05-20 14:54, 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


I'd use a few regular expressions:

 >>> from re import sub
 >>> tuple = '(0128, 020, 008,012, 255)'
 >>> sub( " 0*", " ", tuple ) # leading zeroes following space(s)
'(0128, 20, 8,012, 255)'
 >>> sub( ",0*", ",", tuple ) # leading zeroes following comma
'(0128, 020, 008,12, 255)'
 >>> sub( "\(0*", "(", tuple ) # leading zeroes after opening parend
'(128, 020, 008,012, 255)'

Each step could be written as "tuple = sub( ..."

 >>> tuple = sub( " 0*", " ", tuple ) # following space(s)
 >>> tuple = sub( ",0*", ",", tuple ) # following comma
 >>> tuple = sub( "\(0*", "(", tuple ) # after opening parend
 >>> tuple
'(128, 20, 8,12, 255)'
 >>>


Or, if you like to make your code hard to read and maintain, you could
combine them all into a single expression:

 >>> sub( " 0*", " ", sub( ",0*", ",", sub( "\(0*", "(", tuple ) ) )
'(128, 20, 8,12, 255)'
 >>>

-- 
Michael F. Stemper
What happens if you play John Cage's "4'33" at a slower tempo?



More information about the Python-list mailing list