【问题标题】:I converted a int to a str but I get "object of type 'int' has no len()"我将 int 转换为 str 但我得到“'int'类型的对象没有 len()”
【发布时间】:2019-12-01 12:05:40
【问题描述】:

这个函数应该返回一个数字的数字总和。

我使用new = str(x)将新变量转换为字符串

def digital_root(x):
    sum=0
    new = str(x)
    while len(new) > 2:
        for i in new:
            sum = sum + int(i)
        new = sum

    if len(str(new))==2:
        return int(new[0])+int(new[1])

调用例如digital_root(65536)。但它返回:

TypeError: 'int' 类型的对象没有 len()

【问题讨论】:

  • 提示:当你说new = sum时,new现在有什么类型?
  • 发布有关错误的问题时,请发布完整的错误跟踪,从Traceback (most recent call last) 开始直到结束
  • digital_root = lambda x: sum(map(int, str(x)))

标签: python string int


【解决方案1】:

是的,你转换了你的变量,所以当你第一次进入while循环时,它是一个字符串。

但是,在循环中执行new = sum,其中sum 的类型为int。所以循环的第二次检查因为object of type 'int' has no len()而中断。

你想要的是:

def digital_root(x):
    sum=0
    new = str(x)
    while len(new) > 2:
        for i in new:
            sum = sum + int(i)
        new = str(sum) # make sure each time you leave, your type is str

    if len(new)==2: # here you don't have to make it a string anymore
        return int(new[0])+int(new[1])

【讨论】:

    猜你喜欢
    • 2022-01-09
    • 1970-01-01
    • 1970-01-01
    • 2019-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-21
    相关资源
    最近更新 更多