How to replace a word in a string in Python?

Ways to replace a word in a string in Python

The replace() function is a part of the string class and can replace substrings in a string. We can use this function to replace a word in a string in Python.

To replace a word in a string in Python:

  1. Use the replace() function.

See the code below.

    
# Replace a word in a string in Python
string1 = "educatejava"
string2 = string1.replace('java','python')
print(string2)
# Output: educatepython

We can specify the total replacements to be done using the count parameter. By default, all occurrences are replaced.

Alternatively, we can also use regular expressions. We use the re module to work with regular expressions in Python.

The re.sub() can replace a substring from a string that matches a given regex pattern.

To replace a word in a string in Python:

  1. Use the re.sub() function.

See the code below.

    
# Replace a word in a string in Python
import re
string1 = "educatejava"
string2 = re.sub('java','python',string1)
print(string2)
# Output: educatepython

Another function that works similarly to this is the re.subn() function. It works like the re.sub() function but provides the result in a different format.

The final result is returned in a tuple with the new string and the total matches encountered.

To replace a word in a string in Python:

  1. Use the re.subn() function.

See the code below.

    
# Replace a word in a string in Python
import re
string1 = "educatejava"
string2 = re.subn('java','python',string1)
print(string2)
# Output: ('educatepython', 1)

To conclude

This tutorial demonstrated several methods to replace a word in a string in Python. The most straightforward method is to use the replace() function. We can also use regular expressions as demonstrated. The use of re.sub() and re.subn() functions are demonstrated.

Explore more from this category at Python Strings. Alternatively, search and view other topics at All Tutorials.