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:
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": ...