0

I have a python str object like this and i want to convert this into a list

l = "['Incorrect password.$', 'Login failed']"  --- type <str>

expected output

l = ['Incorrect password.$', 'Login failed']  ---- type <list>

Trial 1:

p = list(l)

it makes l as ['[', "'", 'I', 'n', 'c', 'o', 'r', 'r', 'e', 'c', 't', ' ', 'p', 'a', 's', 's', 'w', 'o', 'r', 'd', '.', '$', "'", ',', ' ', "'", 'L', 'o', 'g', 'i', 'n', ' ', 'f', 'a', 'i', 'l', 'e', 'd', "'", ']']

Trial 2:

  l.split(',')

second method is not favourable as the list element itself may contain comma in between.

How should i proceed? Any hint is appreciated.

prashantitis
  • 1,797
  • 3
  • 23
  • 52
  • 1
    Well, you'd `eval()` that string if you want to interpret it as if it was actually python code... but why are you doing this? – Jeff Mercado Feb 23 '18 at 17:24
  • if every string you want is in between this ‘ you can parse it. and check that character if it is escaped every time – aeb-dev Feb 23 '18 at 17:26

2 Answers2

6

Use the ast module

import ast
l = "['Incorrect password.$', 'Login failed']"
print l, type(l)
l =  ast.literal_eval(l)
print l, type(l)

Output:

['Incorrect password.$', 'Login failed'] <type 'str'>
['Incorrect password.$', 'Login failed'] <type 'list'>
Rakesh
  • 81,458
  • 17
  • 76
  • 113
1
eval(l)

eval() is a built-in function that will evaluate the code.

Xantium
  • 11,201
  • 10
  • 62
  • 89
Oren E
  • 19
  • 1
  • 2