In this article, we will be understanding the functionality of Python replace() function.
Python replace() function with String
Python has in-built string.replace() function to replace a porting of a string with another string.
The string.replace() function
accepts the string to be replaced and the new string which u want to replace the old string with.
Syntax:
string.replace("old string","new string", count)
old string
: The string to be replaced.new string
: The new portion of the string that you wish to place in the old string’s position.count
: It represents the number of times, we want the string to be replaced by the new string.
Example 1: Replacing old string with a new string passed to the function
inp_str = "Python with AskPython"
res = inp_str.replace("AskPython", "AP")
print("Original String:",inp_str)
print("Replaced String:",res)
In the above snippet of code, we have replaced the string – ‘AskPython’ with ‘AP’.
Output:
Original String: Python with AskPython
Replaced String: Python with AP
Replacing Specified Number of Instances
Now let’s use the count parameter to specify the number of instances of a string that we want to replace.
Example 2: Using count
as a parameter to the replace() function
inp_str = "abcdaaseweraa"
res = inp_str.replace("a", "x",2)
print("Original String:",inp_str)
print("Replaced String:",res)
In this example, we have passed the input string as – ‘abcdaaseweraa’. Further, we have passed the character ‘a’ of the original string to be replaced by the character ‘x’.
Here, the count is set to 2 i.e. only the first two encountered character ‘a’ will be replaced by the character ‘x’. The remaining encountered ‘a’ will be unlaterted and will remain the same.
Output:
Original String: abcdaaseweraa
Replaced String: xbcdxaseweraa
Python replace() function with Pandas module
The replace() function can also be used to replace some string present in a csv or text file.
Python Pandas module is useful when it comes to dealing with data sets. The pandas.str.replace() function
is used to replace a string with another string in a variable or data column.
Syntax:
dataframe.str.replace('old string', 'new string')
We will be using the following data set in the below example:

Example:
import pandas
df = pandas.read_csv("C:/IMDB_data.csv", sep=",",encoding='iso-8859-1')
df['Language']=df['Language'].str.replace("English","Hindi")
In the above snippet of code, pandas.read_csv() function
is used to import and load a dataset.
As seen above in the data set, we have selected the ‘Language’ column in order to replace ‘English’ with ‘Hindi’.
Output:

Conclusion
So, as we have seen above, the Python replace() function is very useful when it comes to replacing a portion of a string for a huge data set.
I would strongly recommend the readers to go through the Pandas tutorial to learn further about how to interact with CSV files in Python.
References
- Python replace() function article on JournalDev