![](/img/trans.png)
[英]python format string TypeError: not all arguments converted during string formatting
[英]Python: TypeError - not all arguments converted during string formatting
我正在编写一个基本的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)
但是,运行此脚本后,出现以下错误:
TypeError: not all arguments converted during string formatting
我的代码有什么问题?
这种情况发生时n
在表达式n%i
是一个字符串,不是一个整数。 您将x
is_prime()
字符串,然后将其传递给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
将整数传递给is_prime()
:
is_prime(int(x[i:]))
字符串的%
运算符用于字符串格式化操作 。
您似乎忘记了从truncable()
返回任何内容; 也许您想添加:
return li
在末尾?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.