使用字符串op向python字典添加变量

2024-05-14 12:51:47 发布

您现在位置:Python中文网/ 问答频道 /正文

尝试添加一个字符串,该字符串包含一个变量,该变量可以是我的字典.临时工只是一个随机的文本字符串,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)

没有这些工作,我做错什么了?在

^{pr2}$

输出:

K60ICFRZVEIORPY9CAJ38ION67EELK公司

{'Accept-Encoding':'标识','主机':'chat.site.com','Accept':'文本/纯文本', 'User agent':'客户端Python urllib/2.6','userid':'39','If-n 一个匹配项“:”jrc-”,“Content type”:“text/xml”}

在 在

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

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

也不输出


Tags: 字符串text文本nonestringiftypematch
1条回答
网友
1楼 · 发布于 2024-05-14 12:51:47

如果^{{cd1>}是一个以上元素的^{cd2>}的情况下,上述操作将失败:

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

我相信如果^{cd3>}是^{cd4>}的话,也会失败,原因类似。

应该“工作”的东西是^{cd5>}

*此处的工作是通过不抛出异常来定义的

相关问题 更多 >

    热门问题