split a string of numbers into a list python

Question:

I have a string that contains a random amounts of numbers, these numbers can be like 1, 2, 3 and so, but they can even be 100, 20, 25… so if I’m searching for 14, I will find a 14 in 144, if the string contains it. I Have to split them into a list of integers. Here’s what I tried:

def to_list(string):
    result_list = []
    for idx in range(len(string)):
      if string[idx] != "0":
        zeros = 0
        for j in string[idx + 1:len(string)]:
          if j == "0":
            zeros += 1
          else:
            result_list.append(string[idx] + "0" * zeros)
            break

    result_list.append(string[-1])
    return result_list
Asked By: clapmemereview

||

Answers:

You can use regex for that

import re
a = "1001010050101"
a = list(map(int, re.findall(r"[1-9]+0*", a)))
print(a)

Answered By: jvx8ss
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.