clapmemereview
clapmemereview

Reputation: 393

split a string of numbers into a list python

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

Upvotes: 0

Views: 107

Answers (1)

jvx8ss
jvx8ss

Reputation: 611

You can use regex for that

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

Upvotes: 5

Related Questions