Python学习笔记:TypeError: not all arguments converted during string formatting 解决

前言

在学习python中难免犯下一些幼稚的错误,为了方便后来人的学习,写下此篇文档。

问题

TypeError: not all arguments converted during string formatting

举例

例如:

 >>> strs=(1,2,3,4)  #创建一个集合
>>> strs
 (1, 2, 3,4)
 >>> print 'strs= %s ' % strs
 Traceback (most recent call last):
   File "<pyshell#43>", line 1, in <module>
     print 'strs= %s ' % str
 TypeError: not all arguments converted during string formatting

原因:1 % 操作符只能直接用于字符串(‘123’),列表([1,2,3])、元组

解决方法

···

print ‘strs= %s’ % (strs,)
strs= (1, 2, 3,4)
也可以用:
print ‘strs= %s,%s,%s,%s’ % sstr
strs= 1,2,3,4
···

#简单解释
说明前后%和后面的参数数量不对应,比如

“`
File “

后面有miles和kilometer两个参数,前面只有一个%f,还有一个打印错的&, 前后不一致; 如果改成

print ‘%f miles is the same as %f km’ % (miles, kilometers)
“`
就可以了

猜你喜欢

转载自blog.csdn.net/lvsehaiyang1993/article/details/80909984