-2

I have this:

st = '"a": "hello", "c": "another, string, with multiple", "b": "hello, world"'

I want to replace the comma by an empty space, but it should only be removed IF the character before it is NOT a double quote (")

So the result of st would be

st = '"a": "hello", "c": "another string with multiple", "b": "hello world"'
trincot
  • 263,463
  • 30
  • 215
  • 251
Ian
  • 11
  • 1
  • 3
    This question strongly suggests that you're trying to solve an easy problem in one piece of code by solving a much harder problem somewhere else -- like, say, trying to convert a stringified dict back to a dict, rather than avoiding stringifying it in the first place (or stringifying it via something like `json` that's easily reversible). – Samwise Jun 01 '22 at 14:12
  • NB: if you would *replace* with a space, you'd expect two consecutive spaces in your example... – trincot Jun 01 '22 at 14:17
  • Does this answer your question? [Regex for matching something if it is not preceded by something else](https://stackoverflow.com/questions/9306202/regex-for-matching-something-if-it-is-not-preceded-by-something-else). Further see [this answer](https://stackoverflow.com/a/18250640/5527985) (it's the opposite of what you want). – bobble bubble Jun 01 '22 at 16:25

2 Answers2

0

If I understand your question right I think that my pseudocode will help you to solve your problem at your required language

for i in st 
    if (st[i] = ",") AND (st[i-1] NOT """)
        POP
    else 
        return 
Spiros
  • 99
  • 10
0

Your string looks like it is JSON, but with the surrounding braces stripped from it.

The best would be to get the original JSON and work with that, but if you don't have access to that, then restore the JSON, parse it, make the replacements, encode it again as JSON, and strip those braces again:

import json

st = '"a": "hello", "c": "another, string, with multiple", "b": "hello, world"'

d = json.loads("{" + st + "}")
for key in d:
    d[key] = d[key].replace(",", " ").replace("  ", " ")

st = json.dumps(d)[1:-1]
trincot
  • 263,463
  • 30
  • 215
  • 251