python修复TypeError:必须是str,而不是int

时间:2018-05-23 17:14:58

标签: python

你好每一个我都有问题,当我试图将食品价格乘以食物数量时

txtReceipt.insert(
    END,
    str(No) + "  " + str(my_text) + '\t\t' +\
    str(my_quantity) + '\t\t' + int(my_quantity) * int(price) + "\n"
)

我有这个问题

TypeError: must be str, not int

2 个答案:

答案 0 :(得分:2)

您需要在连接之前将int对象转换为字符串。 str(int(my_quantity)*int(price))

<强>实施例

txtReceipt.insert(END,str(No)+"  "+ str(my_text)+'\t\t'+str(my_quantity)+'\t\t'+str(int(my_quantity)*int(price))+"\n")

答案 1 :(得分:1)

您无法添加字符串和整数,这就是以下代码段引发异常的原因。

# Trying to add a string and an int raises a TypeError
'\t\t' + int(my_quantity) * int(price)

一种解决方案是将您的int投射到str,就像这样。

# This will now work
'\t\t' + str(int(my_quantity) * int(price))

尽管存在更清晰的字符串生成语法,它会隐式地将对象强制转换为str

使用str.format

'{}  {}\t\t{}\t\t{}\n'.format(
    No, my_text, my_quantity, int(my_quantity) * int(price)
)

使用文字字符串插值

如果您使用的是Python 3.6+,最好的方法是使用f-strings。

f'{No}  {my_text}\t\t{my_quantity}\t\t{int(my_quantity) * int(price)}\n'