KeyError when using .format in string in Python

I have a string and I want to use the .format python function to add some variables to it, this is my string:

'{"auth": {"tenantName": "{Insert String Here}", "passwordCredentials": {"username": "{insert String here}", "password": "{insert String Here}"}}}'

when i use .format as follows:

credentials='{"auth": {"tenantName": "{tenant}", "passwordCredentials": {"username": "{admin}", "password": "{password}"}}}'.format(tenant='me',admin='test',password='123')

This gives me the following error:

KeyError: '"auth"'

Any help? Thanks at Advance.

+4
source share
5 answers

{and }are special characters for formatting strings, as you clearly know, since you use them for {tenant}, {admin}and {password}. All the others {, and }they must be escaped by doubling them. Try:

credentials='{{"auth": {{"tenantName": "{tenant}", "passwordCredentials": {{"username": "{admin}", "password": "{password}"}}}}}}'.format(tenant='me',admin='test',password='123')
+11
source

. json, json ,

>>> import json
>>> data_dict = json.loads(data)
>>> data_dict["auth"]["tenantName"]
u'{Insert String Here}'
+4

.format {} . , , , , , , .

, . .format, . :

credentials='{{"auth": {{"tenantName": "{tenant}", "passwordCredentials": {{"username": "{admin}", "password": "{password}"}}}}}}'.format(tenant='me',admin='test',password='123')

. : http://docs.python.org/2/library/string.html#formatstrings

. : python, .format ?

0

{"auth". , , , "auth" - , .format(). curly_braces, {{.

, , JSON. json.

0

, . , , {} . , , .format , `{...} ', , . :

credentials='["auth": ["tenantName": "{tenant}", "passwordCredentials": ["username": "{admin}", "password": "{password}"]]}'.format(tenant='me',admin='test',password='123')

a

credentials.replace("[","{")
credentials.replace("]","}")
-1

All Articles