Replace () function in python

Python Methods and Functions

Python has a built-in function string.replace () to replace a string with another string. The string.replace () function accepts the string to replace and the new string you want to replace the old one with.

 Replace function

Syntax:



 string.replace (" old string "," new string ", count) 
  • old string : string, which you want to replace.
  • new string : The new part of the string that you want to place at the position of the old string.
  • count : number of times.

Example 1: Replacing the old line with a new line passed to the function

 inp_str = "Python with pythononline "res = inp_str.replace (" pythononline "," AP ") print (" Original String: ", inp_str) print (" Replaced String: ", res) 

In the above code snippet, we replaced the string "pythononline" with "AP".

Output:

 Original String: Python with pythononline Replaced String: Python with AP 



Replacing the specified number of instances

Now let's use the count parameter to specify the number of instances of the row to which we want to replace.

Example 2: Using count as a parameter to replace ()

 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 && # 8216; abcdaaseweraa & # 8217 ;. In addition, we passed the character "a" of the original string, which must be replaced with the character "x".

Here the counter is set to 2, i.e. only the first two "a" characters encountered will be replaced with the "x" character. The rest of the letters "a" encountered will not be added later and will remain the same. 

Exit:



 Original String: abcdaaseweraa Replaced String: xbcdxaseweraa 



The replace () function with the 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 for working with datasets. 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') 

In the following example, we will use the following dataset:

Input Dataset

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 code snippet, the pandas.read_csv () function is used to import and load the dataset.

As you can see from the dataset above, we have selected the Language column to replace "English" with "Hindi".

Output:







Get Solution for free from DataCamp guru