输出中同一行的多个类型

2 投票
2 回答
6848 浏览
提问于 2025-04-17 17:16

我的目标是代码中的最后一行打印输出,但我总是遇到这个错误:TypeError: 不支持的操作数类型:'int' 和 'str'。有没有快速的方法只改变输出部分,让这个变得可能?我还是需要先把它们转换成整数,但在这个输出的情况下,我需要在整数旁边加上“人口”和“面积”这两个词!

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] )

2 个回答

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]))
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]))

撰写回答