371

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

AlSub
  • 1,384
  • 1
  • 14
  • 33
Dewsworld
  • 13,367
  • 23
  • 68
  • 104
  • 16
    FWIW, I had the same confusion. Google "python string replace" took me to old deprecated string functions in python 2.7. IMHO, that section could use a big bold box explaining "string.xxx()" vs "xxx(string)", and directing people to the non-deprecated string methods, e.g. to http://docs.python.org/library/stdtypes.html#string-methods – ToolmakerSteve Dec 13 '13 at 22:43
  • 17
    Python documentation is an absolute shambles considering it is touted as an ideal first language. Quite often the stuff is there, but because of the poor way its organized, its often not indexed well by search engines or even their own site. Look at ToolMakerSteve's link, core string functions are lumpted in to standard types. This does not come up when you search for string functions. – Andrew S Oct 28 '16 at 00:43
  • 19
    To be clear: string.replace() is actually not deprecated on Python 3. – sboggs11 Apr 27 '18 at 18:55
  • 3
    It's in the built-in types for 3.x https://docs.python.org/3.7/library/stdtypes.html#str.replace – JerodG Nov 05 '18 at 15:31
  • 3
    Sometimes people write "str.replace" when they mean [your string variable].replace. Because 'str' is also the name of the relevant class, this can be confusing. – TextGeek Aug 10 '19 at 15:52

9 Answers9

400

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

Example:

>>> 'Hello world'.replace('world', 'Guido')
'Hello Guido'
Boris Verkhovskiy
  • 14,854
  • 11
  • 100
  • 103
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • 6
    The "re" (regular expression) module has alternatives for (some? all?) deprecated string functions. In this case, `re.sub()`. – ToolmakerSteve Dec 13 '13 at 22:19
  • 13
    @ToolmakerSteve: `string` functions are deprecated. `str` methods are not. – Ignacio Vazquez-Abrams Dec 13 '13 at 22:21
  • 7
    FWIW, Whenever I google, I seem to end up at the old deprecated string functions. Here is the link to the (not deprecated) string methods. http://docs.python.org/3.3/library/stdtypes.html#string-methods ~or_for_2~ http://docs.python.org/2/library/stdtypes.html#string-methods – ToolmakerSteve Dec 13 '13 at 22:34
  • 69
    If I have to come to stack overflow to navigate the Python documentation there is a clearly problem. Python team if you are reading. SORT IT OUT! – Andrew S Oct 28 '16 at 00:56
  • Do I have to `import str`? Or maybe `from builtins import str` or maybe even something else? – matth Feb 03 '17 at 16:19
  • @matth: `str` is the built-in string class, therefore `replace()` is a method on all strings. – Ignacio Vazquez-Abrams Feb 03 '17 at 16:27
  • On Python 2 I now get `TypeError: descriptor 'replace' requires a 'str' object but received a 'unicode'`, because I used `unicode_literals`. Any recommendation how to get it to work on Py2 and Py3? – matth Feb 03 '17 at 17:40
  • 3
    Call the method on the object, not the class. `'foo'.replace(...)` – Ignacio Vazquez-Abrams Feb 04 '17 at 01:40
128

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

>>> 'hello, world'.replace(',', ':')
'hello: world'
kev
  • 155,172
  • 47
  • 273
  • 272
28

The replace() method in python 3 is used simply by:

a = "This is the island of istanbul"
print (a.replace("is" , "was" , 3))

#3 is the maximum replacement that can be done in the string#

>>> Thwas was the wasland of istanbul

# Last substring 'is' in istanbul is not replaced by was because maximum of 3 has already been reached
16

You can use str.replace() as a chain of str.replace(). Think you have a string like 'Testing PRI/Sec (#434242332;PP:432:133423846,335)' and you want to replace all the '#',':',';','/' sign with '-'. You can replace it either this way(normal way),

>>> string = 'Testing PRI/Sec (#434242332;PP:432:133423846,335)'
>>> string = string.replace('#', '-')
>>> string = string.replace(':', '-')
>>> string = string.replace(';', '-')
>>> string = string.replace('/', '-')
>>> string
'Testing PRI-Sec (-434242332-PP-432-133423846,335)'

or this way(chain of str.replace())

>>> string = 'Testing PRI/Sec (#434242332;PP:432:133423846,335)'.replace('#', '-').replace(':', '-').replace(';', '-').replace('/', '-')
>>> string
'Testing PRI-Sec (-434242332-PP-432-133423846,335)'
Kushan Gunasekera
  • 7,268
  • 6
  • 44
  • 58
7

Official doc for str.replace of Python 3

official doc: Python 3's str.replace

str.replace(old, new[, count])

Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.

corresponding VSCode's syntax notice is:

enter image description here

str.replace(self: str, old, new, count) -> str

Two method to use str.replace

  • Method 1: use builtin str's replace -> str.replace(strVariable, old, new[, count])
replacedStr1 = str.replace(originStr, "from", "to")
  • Method 2: use str variable's replace -> strVariable.replace(old, new[, count])
replacedStr2 = originStr.replace("from", "to")

Full demo

code:

originStr = "Hello world"

# Use case 1: use builtin str's replace -> str.replace(strVariable, old, new[, count])
replacedStr1 = str.replace(originStr, "world", "Crifan Li")
print("case 1: %s -> %s" % (originStr, replacedStr1))

# Use case 2: use str variable's replace -> strVariable.replace(old, new[, count])
replacedStr2 = originStr.replace("world", "Crifan Li")
print("case 2: %s -> %s" % (originStr, replacedStr2))

output:

case 1: Hello world -> Hello Crifan Li
case 2: Hello world -> Hello Crifan Li

screenshot:

enter image description here

My related (Chinese) post: 【详解】Python 3中字符串的替换str.replace

crifan
  • 12,947
  • 1
  • 71
  • 56
6

Try this:

mystring = "This Is A String"
print(mystring.replace("String","Text"))
Zoe
  • 27,060
  • 21
  • 118
  • 148
Ed Dabbah
  • 79
  • 1
  • 3
2

For readability: appending some characters to a position-fixed word

For example: converting an adjective to an adverb by adding the suffix -ly.

To improve readability, you can put the suffix at the end of the line for readability. To do this, use split() inside replace():

s="The dog is large small"
ss=s.replace(s.split()[3],s.split()[3]+'ly')
ss
'The dog is largely small'
Ooker
  • 1,969
  • 4
  • 28
  • 58
0

Simple Replace:         .replace(old, new, count) .

text = "Apples taste Good."
print(text.replace('Apples', 'Bananas'))          # use .replace() on a variable
Bananas taste Good.          <---- Output

print("Have a Bad Day!".replace("Bad","Good"))    # Use .replace() on a string
Have a Good Day!             <----- Output

print("Mom is happy!".replace("Mom","Dad").replace("happy","angry"))  #Use many times
Dad is angry!                <----- Output
-1
ss = s.replace(s.split()[1], +s.split()[1] + 'gy')
# should have no plus after the comma --i.e.,
ss = s.replace(s.split()[1], s.split()[1] + 'gy')
Zoe
  • 27,060
  • 21
  • 118
  • 148
Harry Binswanger
  • 1,069
  • 10
  • 12
  • 11
    While this code may answer the question, providing additional context regarding why and/or how it answers the question would significantly improve its long-term value. Please [edit] your answer to add some explanation. – CodeMouse92 May 02 '16 at 21:38
  • 2
    The correct answer is previously stated string.replace works in python3. – jorfus Nov 16 '18 at 23:44