Python:TypeError - 不是在字符串格式化期间转换的所有参数

Man*_*edi 0 python

我正在编写一个基本的Python脚本,其代码如下:def is_prime(n):

def is_prime(n):
    i = 2
    while i<n:
        if(n%i == 0):
            return False
        i+=1
    return True

def truncable(num):
    li = []
    x = str(num)
    if(is_prime(num)):
        n = len(x)
        check = ""
        i = 1
        while(i<n):
            if(is_prime(x[i:])):
                check = "True"
            else:
                check = "False"
                break
        if(check == "True"):
            li.append(num)

print truncable(3797)   
Run Code Online (Sandbox Code Playgroud)

但是,运行此脚本后,我收到以下错误:

TypeError: not all arguments converted during string formatting
Run Code Online (Sandbox Code Playgroud)

我的代码出了什么问题?

Mar*_*ers 6

n表达式n%i是字符串而不是整数时,会发生这种情况.你创建x了一个字符串,然后将其传递给is_prime():

>>> is_prime('5')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in is_prime
TypeError: not all arguments converted during string formatting
>>> is_prime(5)
True
Run Code Online (Sandbox Code Playgroud)

将整数传递给is_prime():

is_prime(int(x[i:]))
Run Code Online (Sandbox Code Playgroud)

%字符串上的运算符用于字符串格式化操作.

你似乎忘记了从中返回任何东西truncable(); 也许你想补充一下:

return li
Run Code Online (Sandbox Code Playgroud)

在末尾?