Home > Blockchain >  Cannot remove single quotes from string
Cannot remove single quotes from string

Time:09-29

I got a super weird problem: I got a list of strings which looks like this:

batch = ['{"SageMakerOutput":[{"label":"LABEL_8","score":0.9152628183364868},"inputs":"test"}',
 '{"SageMakerOutput":[{"label":"LABEL_8","score":0.9769203066825867},"inputs":"Alles OK"}',
 '{"SageMakerOutput":[{"label":"LABEL_8","score":0.9345938563346863},"inputs":"F"}']

In each entry of the list I want to remove the single quotes "'" but somehow I cannot remove it with .replace():

for line in batch:
    line = line.replace("'","")

I dont get it

CodePudding user response:

Alright, so judging by your comments and your other post, it seems like what you have are strings, and what you want are dictionaries. I've copied your data from the other post because your data isn't correct in this post (you're missing ] in this post).

Solution

import json

batch = ['{"SageMakerOutput":[{"label":"LABEL_8","score":0.9152628183364868}],"inputs":"test"}',
         '{"SageMakerOutput":[{"label":"LABEL_8","score":0.9769203066825867}],"inputs":"Alles OK"}']

batch = [json.loads(b) for b in batch]

Output:

[{'SageMakerOutput': [{'label': 'LABEL_8', 'score': 0.9152628183364868}],
  'inputs': 'test'},
 {'SageMakerOutput': [{'label': 'LABEL_8', 'score': 0.9769203066825867}],
  'inputs': 'Alles OK'}]

Explanation

Those objects in batch are what are known as JSON objects. They're just strings with a very specific structure. They are analogous to Python's dict type with some very minor differences and can very easily be converted to Python dict objects using Python's built-in json module, which automatically translates those minor differences between JSON and Python (e.g., booleans in JSON strings are true and false, but in Python they need to be True and False).

Notes

Advice to OP and future readers: this post is a classic case of the XY problem. In the future, try to be more clear about your end goal. Your question in this post isn't actually answerable because it's impossible to do what you were asking.

  • Related