ziggy ziggy - 1 month ago 10
Python Question

python function return first non zero strip middle zeros and return last part of number string

Given a number texted string like '0104002' I need a return


Basically return the first part of the number text string when the the number is greater than 0. Then for the second part return the portion that starts with the next nonzero number until the end of the string. number placements will vary for each input, string will not be the same length

I have only been able to get the first part of what I need so far

def lot(num):
for x in num:
if y>0: break
print lot


Answer Source

This seems like something which is trivial for a regex:

>>> import re
>>> re.match(r'^(0*[^0]+)0+([^0].*)$', '0104002').groups()
('01', '4002')

This regex defines two groups which are split by one or more zeroes. The split is defined by the first series of zeroes to appear after the first series of non-zeroes. What comes before that split falls into the first group, and what comes after that falls into the second group.

For anyone who finds regex intimidating, here's the "verbose" explanatory version.

        (        # Begin first group
          0*     # Allow for some number of leading zeroes
          [^0]+  # Match a series of non-zeroes
        )        # End first group
        0+       # Match some series of zeroes (the separator)
        (        # Begin second group
          [^0]   # Match the first non-zero character
          .*     # Match anything afterward
        )        # End second group