Python String Replace() | Method

Python String Replace() | Method
Share it:

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 replaces function can be called from any string object. When called on a string object, it replaces all occurrences of a given string with another string. This method is very fast 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 try to our string replacements.

This function takes 3 arguments. The first argument takes a daily expression, which can be matched against the target string; the second argument is that the replacement string; and eventually, the third argument is that the source string upon which the string replacements are going to be applied. Using regular expressions to do string replacements is extremely handy, as very complex replacements are often implemented during this way. 

However, this power comes at a price. This price being performance. Compiling and executing regular expressions is extremely computationally expensive and therefore the costs can add up – this is often especially the case when multiple regular expressions are utilized 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.
Share it:

python

Post A Comment:

0 comments: