You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python报错TypeError: not all arguments converted during string formatting的修复

TypeError错误原因及修复方案

错误原因

触发TypeError: not all arguments converted during string formatting的核心问题是:列表l中的元素是字符串类型,而你在multiples函数里对字符串i和整数n使用了%运算符。

在Python中%有两种作用:

  • 对整数是取模运算(这是你判断倍数的预期逻辑)
  • 对字符串和其他类型是字符串格式化操作(比如"数字:%d" % 10)

因为你通过input()获取列表元素时直接存入列表,input()默认返回字符串类型,所以执行i%n时,Python会将其识别为字符串格式化操作,但你的字符串里没有对应的占位符(如%d),因此触发格式化参数不匹配的错误。

修复方法

只需在将输入元素添加到列表时,把字符串转换成整数即可,修改append(input())为append(int(input()))。

修复后的完整代码:

def multiples(l,n):
    count=0
    for i in l:
        if(i%n==0):
            count+=1
    return count
m=input("no of elements: ")
l=[]
print("enter elements: ")
for i in range(int(m)):
    l.append(int(input()))  # 添加int()完成类型转换
n=int(input("enter no to find no.of multiples: "))
print(multiples(l,n))

修改后列表中的元素全部为整数,i%n会执行预期的取模运算,判断元素是否为n的倍数,不会再触发格式化错误。

内容的提问来源于stack exchange,提问作者Harish 99

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 22:00:10