【问题标题】:Add variable to python dictionary with string operator使用字符串运算符将变量添加到 python 字典
【发布时间】:2013-03-01 01:41:31
【问题描述】:

尝试向我的一个字典添加一个包含变量的字符串,该变量可以是任何内容。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', '用户代理': '客户端 Python-urllib/2.6', 'userid': '39', 'If-n one-match': 'jrc-', 'Content-type': 'text/xml'}

这很奇怪,因为 temp 自己的输出很好,但在字典中却没有

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

也不输出

【问题讨论】:

  • 我把双引号改成了单引号。我认为这只是一个错字?
  • “不工作”是什么意思?具体说明问题。
  • temp 的值是多少?例如,我们如何确定它不是一个空字符串?
  • 既然你没有说到底是什么不工作,语法看起来不错,字典被称为headers - temp 是否有可能有一些不安全的字符? HTTP 标头仅限于 ASCII 范围 - temp 是否有一些 Unicode 字符或换行符?

标签: python string dictionary


【解决方案1】:

如果temp 是具有多个元素的tuple,则上述操作将失败:

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-09
    • 1970-01-01
    • 2013-11-25
    相关资源
    最近更新 更多