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

调用Python静态类方法时遇‘Type 'str'无__setitem__属性’错误怎么办?

为什么调用静态类方法时会出现“Type 'str' doesn't have expected attribute 'setitem'”错误?

这个错误和静态方法本身没关系,核心问题是Python里的字符串是不可变类型——你代码里用to_convert[to_convert.index(',')] = '.'试图通过索引直接修改字符串内容,但不可变类型不支持这种赋值操作,__setitem__就是实现索引赋值的方法,字符串没有这个方法所以触发报错。

给你几种可行的修正方案:

方案1:用字符串replace()方法(最简洁)

直接调用字符串自带的替换方法,一行搞定需求:

@staticmethod
def replace_region_decimal_sign(to_convert):
    return to_convert.replace(',', '.')

方案2:转列表修改后转回字符串

把字符串转成可变的列表,修改指定位置的元素后,再拼接回字符串:

@staticmethod
def replace_region_decimal_sign(to_convert):
    str_list = list(to_convert)
    comma_pos = str_list.index(',')
    str_list[comma_pos] = '.'
    return ''.join(str_list)

方案3:切片拼接

通过字符串切片拆分出逗号前后的内容,再和点符号拼接成新字符串:

@staticmethod
def replace_region_decimal_sign(to_convert):
    comma_pos = to_convert.index(',')
    return to_convert[:comma_pos] + '.' + to_convert[comma_pos+1:]

以上三种方法调用Calculator.replace_region_decimal_sign("1,23")都会返回"1.23",完美解决报错问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 23:52:05