Python How to remove \ "from a string

I got this code from somewhere on the Internet and saved it in a variable called "doc".

doc = """{"Grade": " \"B+\" "}""" 

I want the document to print

 {"Grade": " B+ "} 

So, I can use ast.literal_eval () to convert the word doc to a dictionary.

But when I try:

 print(doc) 

He prints:

 {"Grade": " "B+" "} 

This is not what I want, because then ast.literal_eval () will not work.

Or:

 print(doc.replace("\"", '')) 

which gives me:

 {Grade: B+ } 

It completely removes the double quote, which I don't want, because ast.literal_eval () gives an error.

So how can I change the "doc" so that

 doc = """{"Grade": " \"B+\" "}""" 

can print the following code after some work?

 {"Grade": " B+ "} 

Thanks in advance!

+5
source share
2 answers

We can simply convert duplicate double quotes to a single set of double quotes with re.sub() :

 In [95]: doc = """{"Grade": " \"B+\" "}""" In [96]: doc Out[96]: '{"Grade": " "B+" "}' In [98]: re.sub(r'["]\s*["]', '"', doc) Out[98]: '{"Grade": "B+"}' In [99]: import ast In [101]: doc = re.sub(r'["]\s*["]', '"', doc) In [102]: ast.literal_eval(doc) Out[102]: {'Grade': 'B+'} 
+2
source

Ok I assume that you have a line in the form {"key": "value"} , in which the value can contain quotes without quotes. In your example, we have Grade for the key and "B+" for the value.

In this case, you can either remove the inner quotation marks or quote them correctly, but you must split the string to determine the value

 start, value, last = re.match(r'(\s*{\s*".*?"\s*:\s*")(.*)("\s*})', doc).groups() 

Then you can easily handle quotation marks in terms of values:

 fixed = value.replace('"', "") # remove quotes 

or

 fixed = value.replace('"', r'\"') # correctly quotes the double quotes 

Then you can successfully write:

 d = ast.litteral_eval(start + fixed + last) 

and get either {'Grade': ' B+ '} or {'Grade': ' "B+" '}

+1
source

All Articles