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

Python代码报错IndexError:替换索引0超出位置参数元组范围求助

问题排查与解决

错误原因

你代码里的print语句使用了无命名的{}占位符,但format方法传入的是关键字参数(name=self.name, os=self.os),两者不匹配:

  • 无命名{}占位符需要对应位置参数,按顺序传入值;
  • 关键字参数需要对应命名占位符(如{name}、{os})才能正确匹配。

这种不匹配导致Python无法找到对应位置的参数,抛出IndexError: Replacement index 0 out of range for positional args tuple错误。

解决方法

方法1:使用命名占位符匹配关键字参数

修改print语句的占位符,与format的关键字参数对应:

class Apple_Product:
    os = " "
    def __init__(self,name):
        self.name = name

    def check_operating_system(self):
        print("This {name} is running {os}.".format(name=self.name, os=self.os))

class iPhone(Apple_Product):
    os = "iOS16"

iPhone13Pro = iPhone("iPhone 13 Pro")
iPhone13Pro.check_operating_system()

方法2:改用位置参数传递

直接按占位符顺序传入参数,去掉关键字标识:

class Apple_Product:
    os = " "
    def __init__(self,name):
        self.name = name

    def check_operating_system(self):
        print("This {} is running {}.".format(self.name, self.os))

class iPhone(Apple_Product):
    os = "iOS16"

iPhone13Pro = iPhone("iPhone 13 Pro")
iPhone13Pro.check_operating_system()

推荐写法:使用f-string(Python3.6+)

f-string可以直接在字符串中嵌入变量,语法更简洁直观:

class Apple_Product:
    os = " "
    def __init__(self,name):
        self.name = name

    def check_operating_system(self):
        print(f"This {self.name} is running {self.os}.")

class iPhone(Apple_Product):
    os = "iOS16"

iPhone13Pro = iPhone("iPhone 13 Pro")
iPhone13Pro.check_operating_system()

内容的提问来源于stack exchange,提问作者Yilin Zuo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 15:06:46