lobjc
lobjc

Reputation: 2961

How do I properly convert a string to a list

I have a function that returns a message as a string as follows:

 l = ['["sure","kkk"]', '["sure","ii"]']

I have tried to remove the "'" character through an iteration but its not working for me. This is my code:

print([item.replace('\'["','"').replace('"]\'','"') for item in l])

Is there a better way to do this since I want the results as this:

l = [["sure","kkk"], ["sure","ii"]]

Upvotes: 0

Views: 30

Answers (2)

lmiguelvargasf
lmiguelvargasf

Reputation: 70003

Alternatively, you can also use ast.literal_eval (see the docs) as follows:

import ast

l = ['["sure","kkk"]', '["sure","ii"]']
l = [ast.literal_eval(s) for s in l]
print(l)  # [['sure', 'kkk'], ['sure', 'ii']]

Upvotes: 1

trincot
trincot

Reputation: 351369

Those are JSON encoded strings, so you should use the json API for that and not try to parse it "yourself":

import json

l = ['["sure","kkk"]', '["sure","ii"]']
l = [json.loads(s) for s in l]
print(l)  # [['sure', 'kkk'], ['sure', 'ii']]

Can also be achieved with map instead of list comprehension:

l = list(map(json.loads, l))

Upvotes: 1

Related Questions