Search code examples
stringlistsplitintegerenumerate

Splitting a sequence of number into a list (Python)


I wanted to ask you how can I split in Python for example this string '20020050055' into a list of integer that looks like [200, 200, 500, 5, 5].

I was thinking about enumerate but do you have any example of a better solution to accomplish this example? thanks


Solution

  • One approach, using a regex find all:

    inp = '20020050055'
    matches = re.findall(r'[1-9]0*', inp)
    print(matches)  # ['200', '200', '500', '5', '5']
    

    If, for some reason, you can't use regular expressions, here is an iterative approach:

    inp = '20020050055'
    matches = []
    num = ''
    for i in inp:
        if i != '0':
            if num != '':
                matches.append(num)
            num = i
        else:
            num = num + i
    matches.append(num)
    
    print(matches)   # ['200', '200', '500', '5', '5']
    

    The idea here is to build out each match one digit at a time. When we encounter a non zero digit, we start a new match. For zeroes, we keep concatenating them until reaching the end of the input or the next non zero digit.