遵循 string.replace ( http://docs.python.org/library/string.html ) 的 Python 文档:
string.replace(str, old, new[, maxreplace])
Return a copy of string str with all occurrences of substring old replaced by new. If the optional argument maxreplace is given, the first maxreplace occurrences are replaced.
使用给定的格式会产生以下错误:
>>> a = 'grateful'
>>> a.replace(a,'t','c')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: an integer is required
你需要重复“str”似乎很奇怪,从错误中我猜到我的第三个参数被用于 maxreplace。
格式:
string.replace(old, new)
似乎确实按预期运行。
我想知道我是否误解了什么,Python 文档中给出的形式实际上在某些方面是正确的。
最佳答案
我认为您在这里(以及大多数答案的困惑)是 string
模块和 str
内置类之间的不同。它们是完全独立的东西,即使在功能上有很多重叠。
string.replace(s, old, new)
是一个自由函数,而不是一个方法。您无法将其称为 s.replace(old, new)
,因为 s
不能是 string
模块的实例。
str.replace(self, old, new)
是一个方法。与任何其他方法(类方法和静态方法方法除外)一样,您可以(并且通常会这样做)通过 str
实例调用它,如 s.replace(old, new)
,其中 s
自动成为 self
参数。
你也可以通过类调用一个方法,所以str.replace(s, old, new)
结果和s.replace(old, new)完全一样
。碰巧的是,如果 s
是一个 str
,这与 string.replace(old, new)
的作用完全相同。但由于历史原因,这确实是一个巧合。
作为旁注,您几乎不想调用 string
模块中的函数。它们大多是 Python 早期版本的遗留物。事实上,string.replace
列在文档的“已弃用的字符串函数”部分下,您可能会在那里寻找的大多数其他函数也是如此。整个模块没有被弃用的原因是它有一些不属于 str
(或 bytes
或 unicode
) 类,例如像 string.digits
这样的常量。
关于python - string.replace 的正确形式是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12501100/