2

I have to build a string like this

{ name: "john", url: "www.dkd.com", email: "john@fkj.com" }

where john, www.dkd.com and john@fkj.com 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","john@fkj.com")

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

4

6 回答 6

2

看起来您正在尝试构建(格式错误的)JSON,或者只是构建字典字符串的奇怪方式......

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

或者:

import json
print json.dumps (d)
于 2013-07-01T10:30:43.893 回答
2

您需要逃脱{并将}它们加倍:

s1 = "{{'name:' {0},'url:' {1},'emailid:' {2}}}"
print s1.format("john","www.dkd.com","john@fkj.com")
于 2013-07-01T10:19:57.400 回答
1

您可以使用字符串格式,它应该可以完美地工作..

s1 = "{'name:' '%s','url:' '%s','emailid:' '%s'}" % ("john","www.dkd.com","john@fkj.com")
于 2013-07-01T10:18:57.307 回答
1

发生此错误是因为您没有转义起始大括号,然后将其解释format()named field

格式字符串语法文档中所述:

如果您需要在文字文本中包含大括号字符,可以通过加倍来转义:{{ 和 }}。

所以:

s1 = "{{'name:' {0},'url:' {1},'emailid:' {2}}}"
print s1.format("john","www.dkd.com","john@fkj.com")

将输出:

"{'name:' john,'url:' www.dkd.com,'emailid:' john@fkj.com}"
于 2013-07-01T10:26:43.763 回答
1

根据您所需的格式,这应该有效:

>>> s1 = "{name: '%s',url: '%s',emailid: '%s'}" % ("john","www.dkd.com","john@fkj.com")
>>> s1
"{name: 'john',url: 'www.dkd.com',emailid: 'john@fkj.com'}"
于 2013-07-01T10:27:11.333 回答
0

或者你可以简单地做到这一点:

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

这是工作解决方案http://ideone.com/C65HnB

于 2013-07-01T10:31:07.770 回答