2

我的目标是代码中的最后一个打印行,但我真的做不到,因为我一直收到此错误TypeError:unsupported operand type(s) for +: ' int' and ' str'。有没有一种快速的方法来仅更改输出部分以使其成为可能?我仍然需要首先将它们转换为 int,但在这个输出的情况下,我需要在 int 旁边有“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] )
4

2 回答 2

4

您必须使用以下命令将它们转换为字符串str()

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

或者将它们作为参数传递并让我们print处理它:

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

虽然在这一点上,我会使用字符串格式:

print('{}- \tArea: {}\tPopulation: {}'.format(reply, rountries[reply][0], rountries[reply][1]))
于 2013-02-27T05:20:13.267 回答
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]))
于 2017-02-08T20:28:54.853 回答