6

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)?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Olivier Pons
  • 15,363
  • 26
  • 117
  • 213

3 Answers3

21

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
dmeister
  • 34,704
  • 19
  • 73
  • 95
  • 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', '')
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Thomas Zoechling
  • 34,177
  • 3
  • 81
  • 112
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
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • 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