Reputation: 2961
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
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
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