-2

任意の変数を含む文字列を辞書の 1 つに追加しようとしています。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

temptuple複数の要素を持つ場合、上記は失敗します。

 "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 に答える