-2

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].

CodeKid
  • 13
  • 5

2 Answers2

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