I have a string and I want to use .format function of python to add some variables in it on runtime, This is my string :
'{"auth": {"tenantName": "{Insert String Here}", "passwordCredentials": {"username": "{insert String here}", "password": "{insert String Here}"}}}'
when I use .format like this:
credentials='{"auth": {"tenantName": "{tenant}", "passwordCredentials": {"username": "{admin}", "password": "{password}"}}}'.format(tenant='me',admin='test',password='123')
It gives me the following error:
KeyError: '"auth"'
Any Help? Thanks in Advance.
{
and }
are special characters for string formatting, as you clearly are aware, since you are using them for {tenant}
, {admin}
and {password}
. All the other {
s and }
s need to be escaped by doubling them. Try:
credentials='{{"auth": {{"tenantName": "{tenant}", "passwordCredentials": {{"username": "{admin}", "password": "{password}"}}}}}}'.format(tenant='me',admin='test',password='123')
You are using the wrong tool for your trade. You are dealing with json, and you need to use the json library to parse your data and then access your field as a dictionary
>>> import json
>>> data_dict = json.loads(data)
>>> data_dict["auth"]["tenantName"]
u'{Insert String Here}'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With