What regex statement do I need to get each number out of this list and then turn it into a string with each element being the number. For example, if the string is x = "[899, 908, 3260]"
how do I make this list = [899, 908, 3260]
.
Asked
Active
Viewed 49 times
2 Answers
2
I don't think regular expressions is your 1st option to try here.
JSON: Try to parse it as json:
import json
x = "[899, 908, 3260]"
print(json.loads(x))
String functions: Alternatively, some string manipulation:
x = "[899, 908, 3260]"
print(list(map(int, x.strip('][').split(', '))))
Regex: If for some reason you definately need regex, you should use re.findall
:
import re
x = "[899, 908, 3260]"
print(list(map(int, re.findall(r"\d+", x))))
All options mentioned above output:
[899, 908, 3260]

JvdV
- 70,606
- 8
- 39
- 70
0
use eval
function as eval(x)
. But some say it is exposed one.

Suraj Shejal
- 640
- 3
- 19
-
1I would in general recommend NOT using `eval` given that it's a lot slower than for example simply parsing json and it also is a security concern – Exelian Jan 16 '21 at 19:06
-
Also the questions says `using regex`. – Kostas Mouratidis Jan 16 '21 at 19:07