1

I need to turn this string that looks like a list into an actual list -

status = "[['0', '2', '3', '5']]"

and expected result should be

status = ['0', '2', '3', '5']

Any suggestions?

Prashant
  • 402
  • 1
  • 8
  • 24
  • 1
    _"I need to remove Square brackets and Double quotes from python list"_ -> "I need to turn this string that looks like a list into an actual list" – Aran-Fey Apr 16 '18 at 14:31

2 Answers2

3

You can use re.findall:

import re
status = "[['0', '2', '3', '5']]"
new_status = re.findall('\d+', status)

Output:

['0', '2', '3', '5']

However, you can also use ast.literal_eval:

import ast
new_data = ast.literal_eval(status)[0]

Output:

['0', '2', '3', '5']
Ajax1234
  • 69,937
  • 8
  • 61
  • 102
3

The first one is not a list but a string, so you might get along with:

from ast import literal_eval
status = "[['0', '2', '3', '5']]"
status = literal_eval(status)
status = status[0]
print(status)

This yields

['0', '2', '3', '5']

But please consider correcting the string in the first place (where does it come from?).

Jan
  • 42,290
  • 8
  • 54
  • 79