遵循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文档中给出的形式实际上在某种程度上是正确的。
看起来您将字符串模块的“replace”方法与python字符串的“replace”方法混淆了。
将返回“测试”
将返回“测试”
将返回您提到的错误
是的,该文档是正确的,因为它指的是将
string.replace()
用作独立函数。所以你可以这样做:这与将
replace()
作为给定字符串的方法调用不同,如下所示:它们是两种不同的东西,它们有不同的语法,但被设计成具有相同的结果。所以用另一个的语法调用一个会导致错误。例如:
我认为您在这里的困惑(以及大多数答案)是
string
模块和str
内置类之间的不同。它们是完全独立的,即使功能上有很多重叠。string.replace(s, old, new)
是自由函数,而不是方法。无法将其称为s.replace(old, new)
,因为s
不能是string
模块的实例。str.replace(self, old, new)
是一种方法。与任何其他方法(classmethod和staticmethod方法除外)一样,您可以并且通常通过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
这样的常量。相关问题 更多 >
编程相关推荐