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.
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.
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.
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.
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.
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.
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', '')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With