Python replace "0" with 0 in string

Question:

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?

Asked By: Javi Delgado

||

Answers:

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": ...
Answered By: Linus

Not sure why OP claims that replace() does nothing. For clarity:

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

s = s.replace('"0"', '0')

print(s)

Output:

["variable1": 23.5, 24, 32.1, 0; "variable2": 0, 34.4, 983.2, 0; "variable3": ...
Answered By: Stuart
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.