【问题标题】:TypeError - Can't convert 'int' object to str implicitlyTypeError - 无法将“int”对象隐式转换为 str
【发布时间】:2015-12-16 12:13:25
【问题描述】:

当我运行这段代码时,shell 输出错误 'Can't convert 'int' object to str implicitly'。

我已尝试对 StackOverflow 进行其他修复,但无法在我的代码中修复该问题。

import math
while True: 
    try:
        di = input('Input 7 digit number ')
        total = (int(di[0])+int(di[2])+int(di[4])+int(di[6]))*3+(int(di[1])+int(di[3])+int(di[5]))
    if len(str(di)) != 7:
        print('Incorrect')           
    if len(str(di)) == 7:
        print('Okay')
        multiplier = [3,1]
        times = ''
        total = 0     
        for index, digit in enumerate(list(str(di))):            
            total = total + int(digit)*multiplier[index%2]               
            times = times+str(int(digit)*multiplier[index%2])+', '          
        mof10 = total + (10 - total%10)          
        checkdigit = mof10 - total
        final = str(di) + str(checkdigit)
        print(times[:-1]) 
        print(total)
        print(mof10)
        print(checkdigit)
        print(final)
    final = (di[1]+di[3]+di[5])+((di[0]+di[2]+di[4]+di[6])*3)
    final = (final+4)
    Base10=(int(round(final, -1)))
    Check = Base10-final
    checkdigit = int(input('8th number in product code: '))
    if (n8 == Check):
        print('Valid product code')
except ValueError:
    print('Invalid product code')
    break 

错误信息:

Traceback(最近一次调用最后一次):

文件“C:\Documents and Settings\User\Desktop\GTIN-8 product code.py”,第 55 行,在 final = (final+4)

TypeError: 无法将 'int' 对象隐式转换为 str

【问题讨论】:

  • 您能否发布错误消息的完整回溯,而不仅仅是您的错误摘要
  • 是的,抱歉忘了这样做:P
  • 对不起,我对堆栈溢出还不太熟悉...

标签: python python-3.x


【解决方案1】:

您首先将值d1 作为str 获得

di = input('Input 7 digit number ')

然后你得到final by

final = (di[1]+di[3]+di[5])+((di[0]+di[2]+di[4]+di[6])*3)

因此final 也是str,所以你不能这样做

final = (final+4)

因为finalstr4int

【讨论】:

    【解决方案2】:

    您不能在 Python 中将整数添加到字符串中。您需要将它们都转换为整数或字符串。

    final = int(final) + 4  # convert final from string to integer and add 4
    

    final = final + '4'  # append the string '4' to the end of the string final.
    

    更改上面的行将停止错误,但我认为您的代码的其他部分正在使用字符串,而您应该使用整数。

    例如,如果di=1234567,那么di[0]di[1]等都是字符串。

    因此di[0]+di[2]+di[4]+d[6] 是字符串'1357',而不是1+3+5+7=16。而当你执行di[0]+di[2]+di[4]+d[6] * 3 时,字符串会重复三次'135713571357'。

    如果您在代码的开头创建一个整数列表,您可能会发现它最简单:

    di = [int(x) for x in str(di)]
    

    那么di[0]di[1]等等都是整数。

    【讨论】:

      猜你喜欢
      • 2012-11-19
      • 1970-01-01
      • 1970-01-01
      • 2015-03-23
      • 2017-07-21
      • 1970-01-01
      • 2017-08-31
      • 2015-12-23
      相关资源
      最近更新 更多