Replace all occurrences of one substring with another substring

suggest change

Python’s str type also has a method for replacing occurences of one sub-string with another sub-string in a given string. For more demanding cases, one can use re.sub.

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

str.replace takes two arguments old and new containing the old sub-string which is to be replaced by the new sub-string. The optional argument count specifies the number of replacements to be made:

For example, in order to replace 'foo' with 'spam' in the following string, we can call str.replace with old = 'foo' and new = 'spam':

>>> "Make sure to foo your sentence.".replace('foo', 'spam')
"Make sure to spam your sentence."

If the given string contains multiple examples that match the old argument, all occurrences are replaced with the value supplied in new:

>>> "It can foo multiple examples of foo if you want.".replace('foo', 'spam')
"It can spam multiple examples of spam if you want."

unless, of course, we supply a value for count. In this case count occurrences are going to get replaced:

>>> """It can foo multiple examples of foo if you want, \
... or you can limit the foo with the third argument.""".replace('foo', 'spam', 1)
'It can spam multiple examples of foo if you want, or you can limit the foo with the third argument.'

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


String Methods:
* Replace all occurrences of one substring with another substring

Table Of Contents
2 Filter
3 List
7 Loops
17 String Methods
22 Reduce
27 Classes
31 Set
42 Tuple
45 Enum
62 Sockets
89 urllib
92 Idioms
104 Stack
105 Profiling
109 Logging
111 os module
118 Mixins
120 ArcPy
126 Arrays
132 2to3 tool
135 Unicode
138 Neo4j
140 Curses
141 Templates
145 heapq
146 tkinter
154 Audio
155 pyglet
157 ijson
160 Flask
161 Groupby
163 pygame
165 hashlib
166 Gzip
167 ctypes
185 pyaudio
186 shelve