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,698
  • 19
  • 47
  • 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 – MrMuMu Feb 23 '18 at 17:26

2 Answers2

5

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
  • 75,210
  • 17
  • 57
  • 95
1
eval(l)

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

Simon
  • 8,992
  • 8
  • 49
  • 76
Oren E
  • 19
  • 1
  • 2