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 array
a = np.array(["Hi, what are you doing?"])
print("Old array:", end = " ")
print(a)
# creating the old character from the array of string
old = "are you"
# creating a new character of strings to replace the old strings
new = "is the boy"
# implementing the char.replace() function
myarray = 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 of a.
  • Line 12: We define the new string, new, to replace old.
  • Line 15: We call the np.char.replace method and store the results in myarray, thereby changing the input array characters from "Hi, what are you doing" to "Hi, what is the boy doing?"

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources