7

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

May I ask you if it's true, why, and if so, how to replace it (with examples)?

Thank you very much.

Olivier Pons
  • 14,839
  • 25
  • 109
  • 203

3 Answers3

21

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

What was removed is the replace function in the string module.

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.

dmeister
  • 33,450
  • 19
  • 69
  • 93
  • Ahh workmates, workmates... Thank you for your answer. I'm sure they're coding a very old way. – Olivier Pons Nov 25 '11 at 11:23
  • Good answer. I would also say thay `"bla".replace("a", "b") can also be rewritren as str.replace("bla", "a", "b"), and maybe that's the origin of the problem. – Baltasarq Jun 26 '19 at 08:07
5

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', '')
Thomas Zoechling
  • 33,778
  • 3
  • 80
  • 111
0

to do this, you can use this code below:

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

and this likely should be the output

    hollo
  • Hello, welcome to stackoverflow! Please keep in mind when answering questions that your answer needs to add significant knowledge over existing answers, so in this case dmeister has already provided this answer (and it was accepted as working), this answer also fails to mention if .replace is depreciated in 3x+ which was the original question. Thank you, and again welcome to SO! – Steve Byrne Dec 29 '18 at 01:52