Where them Python experts at...

WAslayer

Honorary Master
Joined
May 13, 2011
Messages
12,515
Reaction score
13,125
Location
Cape Town
Straight off the bat, I have no Dev background (unless you count bash scripting) and like started yesterday new to python and stuck on something:

Given two variables:

one = ABC
two = '{ "A": "B" }'

I need to replace B in variable two with the variable one:

two = '{"A": "one" }'

So that the end result is:

'{"A": "ABC" }'

Without altering the syntax/format of variable two, as that becomes a body for a POST request and the API is expecting that JSON body..

I have tried:

two = '{"A": " {} " }'.format(one)

And something similar as above, just using f strings as well something with a percentage symbol.. none worked and I am guessing it's because the value is encapsulated in single quotes..
 
In PHP I would hack with regex with preg

I am sure python have something similar
 
Try:
Code:
two = "{{ \"A\”:\”{}\”}}".format(one)

The \” allows you to embed double quotes in a double quoted string and the double {{ and }} prevent these as being used as substitution targets for .format()

….

PythonGuy :cool:
 
3f335afb24c078869c12d2e8283ebdd7.jpg
 
Try:
Code:
two = "{{ \"A\”:\”{}\”}}".format(one)

The \” allows you to embed double quotes in a double quoted string and the double {{ and }} prevent these as being used as substitution targets for .format()

….

PythonGuy :cool:
Python Guy Indeed..!! You, sir, are the man..

This worked a treat..

I did try and escape the double quotes initially, however, had no idea you could do double parentheses..
 
Python Guy Indeed..!! You, sir, are the man..

This worked a treat..

I did try and escape the double quotes initially, however, had no idea you could do double parentheses..

Double braces also work with f-strings!

two = f'{{"A" : "{one}"}}'

{"A" : "ABC"}
 
Some needlessly complicated fun :p

import json

two = json.dumps(dict(json.loads(two), **{'A' : one}))

two = f'{{"A" : "{one}"}}'

{"A" : "ABC"}

f-strings were my first thought as well!
 
Last edited:
Top
Sign up to the MyBroadband newsletter
X