1

I have a string of List of Numbers as follow: (the whole List is stored as a string)

"[{'3', '4', '10', '11'}, {'13', '16', '17', '19'}]"

and i want to select only the numbers and assign them to a list, like this

['3', '4', '10', '11', '13', '16', '17', '19']

i tried to use split() but i have the Following result:

['3', '4', '1', '0', '1', '1', '1', '3', '1', '6', '1', '7', '1', '9']

how can i do This please.

ayloul
  • 31
  • 6
  • You are asking two things at once. The linked question contains the answer to the first problem. – mkrieger1 Jan 30 '21 at 10:45
  • Alternatively, the solution to the problem if you do not care about the data structure is shown here: https://stackoverflow.com/questions/4289331/how-to-extract-numbers-from-a-string-in-python – mkrieger1 Jan 30 '21 at 10:48

1 Answers1

0

regex to rescue

Docs: https://docs.python.org/3/library/re.html#re.findall

# coding=utf8

import re

regex = r"[0-9]+"

test_str = "\"[{'3', '4', '10', '11'}, {'13', '16', '17', '19'}]\""

print(re.findall(regex, test_str, re.MULTILINE))
['3', '4', '10', '11', '13', '16', '17', '19']
Kuldeep Singh Sidhu
  • 3,748
  • 2
  • 12
  • 22
  • yeah this works thanks. but what if i want to have each part separatly like this : ['3', '4', '10', '11'] ['13', '16', '17', '19'] ! – ayloul Jan 30 '21 at 10:54