2

I have to build a string like this

{ name: "john", url: "www.dkd.com", email: "[email protected]" }

where john, www.dkd.com and [email protected] are to be supplied by variables

I tried to do the following

s1 = "{'name:' {0},'url:' {1},'emailid:' {2}}"
s1.format("john","www.dkd.com","[email protected]")

I am getting the following error

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: "'name"

Dont able to understand what I am doing wrong

6 Answers 6

2

Looks like you're trying to build (malformed) JSON or a weird way of just building a string of a dictionary...

d = {'name': 'bob', 'email': 'whatever', 'x': 'y'}
print str(d)

Or:

import json
print json.dumps (d)
Sign up to request clarification or add additional context in comments.

Comments

2

You need to escape { and } by doubling them:

s1 = "{{'name:' {0},'url:' {1},'emailid:' {2}}}"
print s1.format("john","www.dkd.com","[email protected]")

Comments

1

you can use the string formatting, which should work perfectly..

s1 = "{'name:' '%s','url:' '%s','emailid:' '%s'}" % ("john","www.dkd.com","[email protected]")

Comments

1

This error occurs because you didn't escaped the starting curly bracket, which is then interpreted by format() as a named field

As mentioned in the Format String Syntax documentation :

If you need to include a brace character in the literal text, it can be escaped by doubling: {{ and }}.

So:

s1 = "{{'name:' {0},'url:' {1},'emailid:' {2}}}"
print s1.format("john","www.dkd.com","[email protected]")

will output:

"{'name:' john,'url:' www.dkd.com,'emailid:' [email protected]}"

Comments

1

As per your required format, this should work:

>>> s1 = "{name: '%s',url: '%s',emailid: '%s'}" % ("john","www.dkd.com","[email protected]")
>>> s1
"{name: 'john',url: 'www.dkd.com',emailid: '[email protected]'}"

Comments

0

or you could simply do this the easy way:

print '''{ name: "''' + name + '''", url: "''' + url + '''", email: "''' + email + '''" }'''

here is the working solution http://ideone.com/C65HnB

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.