Python 2.7: the 'replace' method of the 'string' object deprecated

Question:

My "workmates" just told me that the replace method of the string object was deprecated and will be removed in 3.xx.

Is it true? And if so, how can I replace it (with examples)?

Asked By: Olivier Pons

||

Answers:

The documentation of 3.2 says nothing about that the replace method of the str type should be removed. I also don’t see any reason why someone should do that.

But the replace function in the string module was removed.

An example:

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

calls the replace method of the str type.

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

calls the replace function of the string module.

Maybe this is what your workmates mixed up. Using the string module function is a very, very old way to do this stuff in Python. They are deprecated, beginning with Python 2.0(!). I am not so good in the history of Python, but I guess probably right when they have introduced object-oriented concepts into the language.

Answered By: dmeister

As far as I understand those deprecation warnings in http://docs.python.org/library/string.html#deprecated-string-functions, only the functions are deprecated. The methods are not.

E.g., if you use:

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

you should replace it with

s.replace('est', '')
Answered By: Thomas Zoechling

To do this, you can use this code below:

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

And this likely should be the output:

hollo
Answered By: 09DeveloperBoy
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.