2013-02-27 36 views
1

我的目標是代碼中的最後一行打印行,但我無法真正獲得此錯誤TypeError:不支持的操作數類型爲+:'int'和'str'。有沒有一種快速的方法來只改變輸出部分以使其成爲可能?我仍然需要將它們轉換爲int,但在這種輸出的情況下,我需要在ints旁邊添加「Population」和「Area」字樣!在同一行輸出中的多種類型

def _demo_fileopenbox():   
    msg = "Pick A File!" 
    msg2 = "Select a country to learn more about!" 
    title = "Open files" 
    default="*.py" 
    f = fileopenbox(msg,title,default=default) 
    writeln("You chose to open file: %s" % f)  
    countries = {} 

     with open(f,'r') as handle: 

     reader = csv.reader(handle, delimiter = '\t') 

     for row in reader: 

     countries[row[0]] = int(row[1].replace(',', '')), int(row[2].replace(',', '')) 

     reply = choicebox(msg=msg2, choices= list(countries.keys())) 

     print(reply) 

     print((countries[reply])[0]) 

     print((countries[reply])[1]) 

     #print(reply + "- \tArea: + " + (countries[reply])[0] + "\tPopulation: " + (countries[reply])[1]) 

回答

3

你必須將它們轉換爲字符串與str()

或者在它們作爲參數傳遞,讓print照顧它:

print(reply + "- \tArea:", countries[reply][0] + "\tPopulation:", countries[reply][1]) 

雖然在這點,我會使用字符串格式:

print('{}- \tArea: {}\tPopulation: {}'.format(reply, rountries[reply][0], rountries[reply][1])) 
+0

是啊哈哈我馬上就收到了! 'reply = choicebox(msg = msg2,choices = list(countries.keys())) output = reply +「 - \ tArea:」+ str((countries [reply])[0])+「\ tPopulation:」 + str((countries [reply])[1]) print(輸出)'謝謝你的回覆! – erp 2013-02-27 05:22:02

+0

@erp:你不需要做'(foo)[0]'。只需寫下'foo [0]',而不用括號。 – Blender 2013-02-27 05:23:04

1

或者你可以用「%」符號來告訴您正在使用的字符串打印線:

print(reply + "- \tArea: %s" % countries[reply][0] + "\tPopulation: %s" + % countries[reply][1]) 

Python3建議使用{:S}代替%S的雖然。起初可能看起來令人生畏,但它不是太糟糕並且可能有用。

print("{reply}-\tArea: {area}\tPopulation: {population}".format(reply=reply,area=countries[reply][0],population=countries[reply][1]))