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

本文通过实例解析了Python中常见的TypeError: not all arguments converted during string formatting错误,详细介绍了该错误产生的原因及其解决方法,并提供了相应的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言

在学习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 "<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)

就可以了

补充

如果还有不会的,可以关注下面的公众号,博主会在24小时内回复。
在这里插入图片描述

评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值