Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python replace "0" with 0 in string

This should be very simple, but I’m quite lost.

I have an string like this:

mystring='["variable1": 23.5, 24, 32.1, "0"; "variable2": "0", 34.4, 983.2, "0"; "variable3": ...'

I wanted to replace all the "0" by 0, without quotes. So the result would be:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

mystring='["variable1": 23.5, 24, 32.1, 0; "variable2": 0, 34.4, 983.2, 0; "variable3": ...'

I mean, I cannot remove ALL the quotes from the string, as the variable names should maintain the quotes.
I tried: myjsona=myjsona.replace('"0"','0'), but of course it does nothing.

Any suggestions?

>Solution :

Regex is useful for this

import re
mystring='["variable1": 23.5, 24, 32.1, "0"; "variable2": "0", 34.4, 983.2, "0"; "variable3": ...'
mystring = re.sub("\"0\"", "0", mystring)

# print(mystring)

To put double quotes in a string, use backslash as shown above, or just use single quotes

Output:

["variable1": 23.5, 24, 32.1, 0; "variable2": 0, 34.4, 983.2, 0; "variable3": ...
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading