【问题标题】:Multiple types in the same line of output同一行输出中的多种类型
【发布时间】:2013-02-12 19:45:42
【问题描述】:

我的目标是代码中的最后一个打印行,但我真的不能,因为我一直收到此错误TypeError: unsupported operand type(s) for +: 'int' 和 '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] )

【问题讨论】:

    标签: python int type-conversion output


    【解决方案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]))
    

    【讨论】:

    • 是的,哈哈,我发布后立即得到它! `回复=选择框(msg=msg2,选择=列表(国家.keys()))输出=回复+“-\tArea:”+str((国家[回复])[0])+“\tPopulation:”+ str((countries[reply])[1]) print(output)` 感谢您的回复!
    • @erp:你不需要做(foo)[0]。只写foo[0],不带括号。
    【解决方案2】:

    或者您可以使用“%”符号告诉打印行您正在使用字符串:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-12
      • 2016-09-20
      • 2021-04-13
      相关资源
      最近更新 更多