Python 我将int转换为str,但得到“int类型的对象没有len()

Python 我将int转换为str,但得到“int类型的对象没有len(),python,string,int,Python,String,Int,此函数用于返回数字的位数和 我使用new=strx将新变量转换为字符串 使用例如digital_root65536调用。但它的回报是: TypeError:类型为“int”的对象没有len 是的,您转换了变量,因此当您第一次进入while循环时,它是一个字符串 但是,在循环中,您执行new=sum,其中sum是int类型的。因此循环的第二次检查中断,因为“int”类型的对象没有len 你想要的是: def digital_root(x): sum=0 new = str(x)

此函数用于返回数字的位数和

我使用new=strx将新变量转换为字符串

使用例如digital_root65536调用。但它的回报是:

TypeError:类型为“int”的对象没有len


是的,您转换了变量,因此当您第一次进入while循环时,它是一个字符串

但是,在循环中,您执行new=sum,其中sum是int类型的。因此循环的第二次检查中断,因为“int”类型的对象没有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])

提示:当你说new=sum时,new现在有什么类型?当发布关于错误的问题时,请发布完整的错误跟踪,从回溯最近一次调用开始,直到enddigital_root=lambda x:summapint,strx
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])