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