-2

尝试添加一个包含变量的字符串,该变量可能是我的一个字典。Temp 只是一个随机的文本字符串,33 个字符长。

lst = ''
temp = ''
def randomstr():
    global lst, temp
    temp = ''
    lst = [random.choice(string.ascii_letters + string.digits) for n in xrange(33)]
    temp = "".join(lst)
headers = {"Content-type": "text/xml", "Accept": "text/plain", "Host": "chat.site.com", "Accept-Encoding": "identity", "User-agent": "Client Python-urllib/2.6", "userid": "39",}
headers["If-none-match"] = "jrc-%s"%temp
headers["If-none-match"] = "jrc-" + temp
headers["If-none-match"] = "jrc-%s" % (temp)

这些都不起作用,我做错了什么?

print temp
print headers

输出:

K60IcFrZveioTrPY9cAJ38IOANj67eElK

{'Accept-Encoding': 'identity', 'Host': 'chat.site.com', 'Accept': 'text/plain', 'User-agent': 'Client Python-urllib/2.6', 'userid ': '39', 'If-n one-match': 'jrc-', 'Content-type': 'text/xml'}

这很奇怪,因为 temp 本身输出很好,但在字典中却没有

headers["If-none-match"] = "jrc-"+str(temp)

也不输出

4

1 回答 1

0

tempis atuple具有多个元素的情况下,上述操作将失败:

 "jrc-%s"%temp #not the right number of elements for formatting
 "jrc-"+temp   #can't concatenate string and tuple

work我相信如果dict出于类似原因,它也会失败。

应该“工作”*的东西是"jrc-"+str(temp)

*这里的工作是通过不抛出异常来定义的

于 2013-03-01T01:45:25.570 回答