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
- old: It is an old substring you want to replace.
- new: It is a new substring that 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 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.
- Python2 is an old style in which the % operator substitutes the string.
- Use the 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.
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.

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.