What is the numpy.char.replace() method from NumPy in Python?
Overview
In Python, the char.replace() function is used to return a copy of an array with all occurrences of the substring old replaced by the substring new.
Syntax
char.replace(a, old, new, count=None)
Parameter value
a: This represents the array of strings or Unicode.old: This represents the old character of strings to be replaced.new: This represents the new character of strings.count: If this parameter value is given, only the first count occurrences are replaced.
Example
import numpy as np# creating the input arraya = np.array(["Hi, what are you doing?"])print("Old array:", end = " ")print(a)# creating the old character from the array of stringold = "are you"# creating a new character of strings to replace the old stringsnew = "is the boy"# implementing the char.replace() functionmyarray = np.char.replace(a, old, new)print('New array:', end = " ")print(myarray)
Explanation
- Line 4: We define a sample string
a. - Line 9: We define a string
old, which is a substring ofa. - Line 12: We define the new string,
new, to replaceold. - Line 15: We call the
np.char.replacemethod and store the results inmyarray, thereby changing the input array characters from"Hi, what are you doing"to"Hi, what is the boy doing?"