What is String Substitution in Python

To substitute string in Python, you can use the “string.replace()” method. The string replace() function is “used to replace a substring with another.”

Syntax

string.replace(old, new, count)

Parameters

  1. old: It is an old substring you want to replace.
  2. new: It is a new substring that would replace the old substring.
  3. 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 one another.

Example

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

Python String Formatting

There are three options available to format the string in Python.

  1. Python2 is an old style in which the % operator substitutes the string.
  2. Use the Python3 format() method.
  3. 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.

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.

sub = "Homer"
print("Yello {}".format(sub))

Output

Yello Homer

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

Conclusion

Python string substitution is a way to replace placeholders in a string with values. It can be done using the format() method, f-strings, or % operator. String substitution is commonly used to dynamically generate strings with variable values.

That is it.

Leave a Comment

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