Python String Replace

Python offers several string replacement methods. Here we will cover two very useful methods.

The first method is the standard string replace:

>>> "foo".replace("foo", "bar")
'bar'

The string replace function can be called from any string object. When called on a string object, it replaces all occurrences of a given string (argument 1) with another string (argument 2). This method is very fast and and suitable for smaller or simple string replacement jobs.

For more complex string replacements we can use the second method, which uses regular expressions, to find the substrings that need to be replaced:

>>> import re
>>> re.sub("foo|bar", "baz", "foobar")
'bazbaz'

In the example we first import the regular expression module “re”. This module contains many regular expression tools and there are multiple ways to do string replacement with this module. Here we use the function >sub< to do our string replacements. This function takes 3 arguments. The first argument takes a regular expression, which will be matched against the target string; the second argument is the replacement string; and finally, the third argument is the source string upon which the string replacements will be applied.

Using regular expressions to do string replacements is very handy, as very complex replacements can be implemented in this way. However, this power comes at a price. This price being performance. Compiling and executing regular expressions is very computationally expensive and the costs can add up – this is especially the case when multiple regular expressions are used in loop structures. Thus, if performance is critical, it needs to be investigated whether regular expressions are really necessary or if the job can be achieved using a less computationally intensive method.

Leave A Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.