[英]“TypeError : not all arguments converted during string formatting” in a Python list
I am writing a recursive function that will print the result of converting a base 10 integer to its equivalent in another base. 我正在编写一个递归函数,该函数将打印将以10为基数的整数转换为另一基数的结果的结果。 At line 11 I receive:
在第11行,我收到:
TypeError: not all arguments converted during string formatting
TypeError:在字符串格式化期间并非所有参数都已转换
Can anyone see what I am doing wrong here and how should I fix it? 有人可以在这里看到我在做什么错吗,应该如何解决?
list = []
def con2base(integer, base):
if integer == 0:
if list == []:
list.insert(0, 0)
return 0
else:
return 0
while integer > 0:
list.insert(0, (integer % base)) <----- This is the offending line
return con2base(integer / base, base)
print ("Enter number to be converted: ")
integer = raw_input()
print ("Enter base for conversion: ")
base = raw_input()
con2base(integer, base)
print list
raw_input
will always return a string object, and never an actual integer. raw_input
将始终返回字符串对象, raw_input
返回实际整数。 You need to convert both of them to int
s first. 您需要先将它们都转换为
int
。
print ("Enter number to be converted: ")
integer = int(raw_input())
print ("Enter base for conversion: ")
base = int(raw_input())
con2base(integer, base)
The reason for the weird error message is that %
is an operator that also works on strings; 错误消息的原因是
%
是同时对字符串起作用的运算符; specifically, it's the string format operator. 具体来说,它是字符串格式运算符。 It lets you create one string with "placeholder" elements, which you can fill in at runtime with other strings.
它使您可以使用“占位符”元素创建一个字符串,您可以在运行时将其与其他字符串一起填充。 So when you get the numbers using
raw_input
and then try to use %
, Python thinks you are trying to do string formatting/substitution. 因此,当您使用
raw_input
获取数字,然后尝试使用%
,Python认为您正在尝试进行字符串格式化/替换。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.