Python’s inbuilt string classes support the sequence type methods. For regular expressions, see the re module for string functions based on regular expressions.
Python String Substitution
To substitute string in Python, use the replace() method. The string replace() is a built-in Python function used to replace a substring with another substring.
Syntax
string.replace(old, new, count)
Parameters
- old – It is an old substring you want to replace.
- new – It is a new substring which would replace the old substring.
- count – The count parameter is the number of times you want to substitute the old substring with a new substring.
Return Value
The replace() function returns a copy of the string where all substring occurrences are substituted with another substring.
Example
Let’s create a string in which we will substitute san with San substring.
string = "san francisco san diego san antonio san jose" # Subsitute san with San at all occurances print(string.replace("san", "San")) # Substitute san with San at first 2 occurances print(string.replace("san", "San", 2))
Output
San francisco San diego San antonio San jose San francisco San diego san antonio san jose
You can see that in the first example, the replace() function substituted san with San in all places in the string. In the second example, it substituted san with San in the first two occurrences.
Python String Formatting
There are three options available to format the string in Python.
- Python2 old style in which the % operator substitutes the string.
- Use Python3 format() method.
- Python f-strings: It allows you to specify expressions inside your string literals.
The % operator to substitute string
The % formatter that accepts C-printf-style format strings. See the below example.
# app.py substitute = "Homer" print("Yello %s" % substitute) print("Yello %s %s" % (substitute, 'simpson'))
Output
Yello Homer Yello Homer simpson
Python format() function to substitute string
Python string format() allows multiple substitutions and value formatting. The format() method concatenates items within a string through positional formatting.
# app.py sub = "Homer" print("Yello {}".format(sub))
Output
Yello Homer
In this example, the format() method substitutes the sub variable and formats the string.
Python 3.6+ f-strings
To create an f-string, prefix the string with the letter “f”. F-strings provide a concise and convenient way to embed python expressions inside string literals for formatting.
sub1 = "Yello" sub2 = "Simpson" print(f"{sub1} Homer {sub2}")
Output
Yello Homer Simpson
F-strings are faster than the two most commonly used string formatting mechanisms.
That is it for Python String Substitution.