0

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"]]

lmiguelvargasf
  • 63,191
  • 45
  • 217
  • 228
lobjc
  • 2,751
  • 5
  • 24
  • 30

2 Answers2

1

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))
trincot
  • 317,000
  • 35
  • 244
  • 286
  • I see you eventually changed the acceptance flag to the `literal_eval` answer. If that is what you need, and not JSON parsing, then it would be good to specify more about the use case: do you get your values from system-to-system communication? Do they come from user input? The nice thing about JSON is that it is highly portable and the [`loads` method is significantly faster than `literal_eval`](https://stackoverflow.com/questions/21223392/why-is-json-loads-an-order-of-magnitude-faster-than-ast-literal-eval). – trincot Jul 13 '20 at 10:00
  • Thanks for this. I will have a look at the details. Kind regards. – lobjc Jul 13 '20 at 10:06
1

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']]
lmiguelvargasf
  • 63,191
  • 45
  • 217
  • 228