Python2.7:字符串对象的替换方法已弃用

2024-06-17 14:54:06 发布

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


Tags: python
3条回答

3.2的documentation没有提到应该删除str类型的replace方法。我也不明白为什么有人要这么做。

删除的是string模块中的replace函数。

例如:

"bla".replace("a", "b")

调用str类型的replace方法。

string.replace("bla", "a", "b")

调用字符串模块的replace函数。

也许这就是你的同事们搞混的。在Python中使用string模块函数是一种非常非常古老的方法。从Python2.0(!)开始就不推荐使用它们。我在Python的历史上不是很在行,但是当他们将面向对象的概念引入到语言中时,我想可能是对的。

为此,可以使用以下代码:

    a = "hello".replace("e", "o")
    print(a)

这很可能是

    hollo

据我所知,http://docs.python.org/library/string.html#deprecated-string-functions中的那些弃用警告,只有函数被弃用。方法不是。

例如,如果您使用:

s = 'test'
string.replace(s, 'est', '')

你应该换成

s.replace('est', '')

相关问题 更多 >