NumPy strings.replace()

The numpy.strings.replace() function replaces occurrences of a substring within each element of an array-like object. It returns a copy of the string with all or a specified number of occurrences replaced.

Syntax

</>
Copy
numpy.strings.replace(a, old, new, count=-1)

Parameters

ParameterTypeDescription
aarray_like (bytes_ or str_ dtype)The input array containing strings.
oldarray_like (bytes_ or str_ dtype)The substring that needs to be replaced.
newarray_like (bytes_ or str_ dtype)The substring that replaces the old substring.
countarray_like (int_ dtype), optionalSpecifies the number of occurrences to replace. If set to -1 (default), all occurrences are replaced.

Return Value

Returns an array with the replaced strings. The output array maintains the same dtype as the input.


Examples

1. Replacing a Substring in a Single String

We replace a specific substring in a single string element.

</>
Copy
import numpy as np

# Define a string
fruit = np.array("apple", dtype="str")

# Replace substring "pp" with "bb"
result = np.strings.replace(fruit, "pp", "bb")

# Print the result
print("Modified string:", result)

Output:

Modified string: abble