Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 2.7: replace method of string object deprecated

Tags:

python

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.

like image 835
Olivier Pons Avatar asked Nov 25 '11 09:11

Olivier Pons


People also ask

Why is replace not working in Python?

You are facing this issue because you are using the replace method incorrectly. When you call the replace method on a string in python you get a new string with the contents replaced as specified in the method call. You are not storing the modified string but are just using the unmodified string.

What to use instead of replace in Python?

subn() If you want to replace a string that matches a regular expression (regex) instead of a perfect match, use the sub() of the re module.

Can Replace be used in string Python?

Python String replace() MethodThe replace() method replaces a specified phrase with another specified phrase. Note: All occurrences of the specified phrase will be replaced, if nothing else is specified.

What is replace () method?

The replace() method returns a new string with one, some, or all matches of a pattern replaced by a replacement . The pattern can be a string or a RegExp , and the replacement can be a string or a function called for each match. If pattern is a string, only the first occurrence will be replaced.


2 Answers

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.

like image 173
dmeister Avatar answered Sep 21 '22 12:09

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', '')
like image 29
Thomas Zoechling Avatar answered Sep 21 '22 12:09

Thomas Zoechling