2013-03-01 67 views
-2

嘗試添加一個字符串,其中包含一個變量,該變量可以是任何字典中的一個.Temp只是一個隨機的字符串,長度爲33個字符。使用字符串運算符將變量添加到python字典中

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

{ '接受編碼': '身份', '主機': 'chat.site.com', '接受': 'text/plain的' , 'User-agent':'Client Python-urllib/2.6','userid':'39','If-n one-match':'jrc-','Content-type':'text/xml '}

其奇怪,因爲臨時輸出在字典

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

也不會輸出

+0

我換了一個雙引號以一個單引號定義。我認爲這只是一個錯字? – mgilson 2013-03-01 01:42:31

+3

「不工作」是什麼意思?具體說明問題。 – StoryTeller 2013-03-01 01:42:50

+0

溫度的價值是什麼?我們如何確定它不是空字符串? – stephenmuss 2013-03-01 01:43:55

回答

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)

*這裏的工作是由不拋出異常