gpt4 book ai didi

python - 同一行输出多种类型

转载 作者:行者123 更新时间:2023-11-28 22:00:17 25 4
gpt4 key购买 nike

我的目标是代码中的最后一行打印,但我真的做不到,因为我不断收到此错误 TypeError: unsupported operand type(s) for +: 'int ' 和 'str'。有没有一种快速的方法可以仅更改输出部分以使其成为可能?我仍然需要首先将它们转换为 int,但在这个输出的情况下,我需要在 ints 旁边加上“人口”和“面积”这两个词!

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

最佳答案

您必须使用 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]))

关于python - 同一行输出多种类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15104693/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com