Replacing One String of Characters with Another Inside a String
You want to replace all occurrences of a string within another string.
Use the replace function.
For example, to replace all occurrences of X with times, you would use:
>>> s = “It was the best of X. It was the worst of X” >>> s.replace(“X”, “times”) ‘It was the best of times. It was the worst of times’ >>> |
Discussion
The string being searched for must match exactly; that is, the search is case-sensitive and will include spaces.
See Also
See Recipe 5.14 for searching a string without performing a replacement.