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])、元组则需要一一匹配操作符。

说白了就是写成 括号加逗号 (strs,)

解决方法

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


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

File "<pyshell#37>", line 1, in <module>
print '%f meters is the same as &f km' % (meters, kilometers)
TypeError: not all arguments converted during string formatting

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

print '%f miles is the same as %f km' % (miles, kilometers)

就可以了

 

猜你喜欢

转载自blog.csdn.net/whatday/article/details/89950305
今日推荐