Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use string.replace() in python 3.x

The string.replace() is deprecated on python 3.x. What is the new way of doing this?

like image 660
Dewsworld Avatar asked Feb 26 '12 09:02

Dewsworld


People also ask

How do I replace a string in a string in Python?

Python String | replace() replace() is an inbuilt function in the Python programming language that returns a copy of the string where all occurrences of a substring are replaced with another substring. Parameters : old – old substring you want to replace. new – new substring which would replace the old substring.

Is there a Replace function for strings in 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.

Why find () and replace () method is used in string Python?

When working with strings in Python, you may need to search through strings for a pattern, or even replace parts of strings with another substring. Python has the useful string methods find() and replace() that help us perform these string processing tasks.


2 Answers

As in 2.x, use str.replace().

Example:

>>> 'Hello world'.replace('world', 'Guido') 'Hello Guido' 
like image 79
Ignacio Vazquez-Abrams Avatar answered Sep 22 '22 00:09

Ignacio Vazquez-Abrams


replace() is a method of <class 'str'> in python3:

>>> 'hello, world'.replace(',', ':') 'hello: world' 
like image 25
kev Avatar answered Sep 21 '22 00:09

kev