为什么我在string.replace()上遇到"AttributeError:'module'对象没有属性'replace'"

Jef*_*eff 8 python string floating-point

导致错误的行是

totalR = totalR + (float(string.replace(contri[0][5],",","")) + float(string.replace(contri[0][6],",","")))
Run Code Online (Sandbox Code Playgroud)

contri [0] [5]和[6]是包含格式为1,000.00的数字的字符串.我在将字符串转换为浮点数之前删除逗号,以便将它们添加到totalR,这是一个浮点数.(创建为totalR = 0.0)我也尝试使用Decimal,但错误也发生在那里.我做了"导入字符串".程序失败并出现错误:

File "mine.py", line 43, in fillDonorData
totalR = totalR + (float(string.replace(contri[0][5],",","")) + float(string.replace(contri[0][6],",","")))
AttributeError: 'module' object has no attribute 'replace'
Run Code Online (Sandbox Code Playgroud)

Dan*_*man 11

string模块中的方法已被弃用多年.你应该replace直接打电话给你的字符串,或者contri[6].

  • 在2.x中,尽管被弃用,[不推荐使用的字符串函数](http://docs.python.org/2/library/string.html#deprecated-string-functions)仍然有效.在3.x中,大多数(包括"替换")不再存在.但是,`string`中仍有大量不推荐使用的函数,常量和类. (2认同)

ala*_*jds 5

它现在str.replace在 Python 3 上运行。

看起来像是重命名的同一事物,具有相同的签名和具有相同含义的文档字符串。