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
Parameter | Type | Description |
---|---|---|
a | array_like (bytes_ or str_ dtype) | The input array containing strings. |
old | array_like (bytes_ or str_ dtype) | The substring that needs to be replaced. |
new | array_like (bytes_ or str_ dtype) | The substring that replaces the old substring. |
count | array_like (int_ dtype), optional | Specifies 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

2. Replacing a Substring in an Array of Strings
We replace a common substring in multiple strings within an array.
</>
Copy
import numpy as np
# Define an array of strings
fruits = np.array(["apple", "banana", "cherry"], dtype="str")
# Replace "a" with "o" in all strings
result = np.strings.replace(fruits, "a", "o")
# Print the results
print("Original strings:", fruits)
print("Modified strings:", result)
Output:
Original strings: ['apple' 'banana' 'cherry']
Modified strings: ['opple' 'bonono' 'cherry']

3. Using the count
Parameter
We replace only the first occurrence of a substring in each string.
</>
Copy
import numpy as np
# Define an array of strings
fruits = np.array(["banana", "banana", "banana"], dtype="str")
# Replace only the first occurrence of "a" with "o"
result = np.strings.replace(fruits, "a", "o", count=1)
# Print the results
print("Original strings:", fruits)
print("Modified strings:", result)
Output:
Original strings: ['banana' 'banana' 'banana']
Modified strings: ['bonana' 'bonana' 'bonana']

4. Replacing a Substring Across Different Words
Replacing a specific letter across multiple words.
</>
Copy
import numpy as np
# Define an array of fruit names
fruits = np.array(["apple", "grape", "pineapple"], dtype="str")
# Replace "p" with "b"
result = np.strings.replace(fruits, "p", "b")
# Print the results
print("Original strings:", fruits)
print("Modified strings:", result)
Output:
Original strings: ['apple' 'grape' 'pineapple']
Modified strings: ['abble' 'grabe' 'bineabble']

The substring "p"
is replaced with "b"
across all elements in the array.