string.replace的正确格式是什么?

2024-05-23 17:44:47 发布

您现在位置:Python中文网/ 问答频道 /正文

遵循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文档中给出的形式实际上在某种程度上是正确的。


Tags: ofthe文档httpnewstringis格式
3条回答

看起来您将字符串模块的“replace”方法与python字符串的“replace”方法混淆了。

string.replace("rest,"r", "t")

将返回“测试”

"rest".replace("r", "t") 

将返回“测试”

"rest".replace("rest", "r", "t") 

将返回您提到的错误

是的,该文档是正确的,因为它指的是将string.replace()用作独立函数。所以你可以这样做:

>>> import string
>>> string.replace("a","a","b")
'b'

这与将replace()作为给定字符串的方法调用不同,如下所示:

>>> 'a'.replace('a','b')
'b'

它们是两种不同的东西,它们有不同的语法,但被设计成具有相同的结果。所以用另一个的语法调用一个会导致错误。例如:

>>> 'a'.replace('a','a','b')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: an integer is required

我认为您在这里的困惑(以及大多数答案)是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(或bytesunicode)类的东西,比如像string.digits这样的常量。

相关问题 更多 >