w3resource

NumPy: Replace a specific character with another in a given array of string values


Write a NumPy program to replace a specific character with another in a given array of string values.

Sample Solution:

Python Code:

# Importing necessary library
import numpy as np 

# Creating a NumPy array containing strings
str1 = np.array([['Python-NumPy-Exercises'], ['-Python-']])

# Displaying the original array of string values
print("Original array of string values:") 
print(str1)

# Replacing '-' with '=' character in the array of string values using np.char.replace() and np.char.strip()
print("\nReplace '-' with '=' character in the said array of string values:")
print(np.char.strip(np.char.replace(str1, '-', '==')))

# Replacing '-' with ' ' character in the array of string values using np.char.replace() and np.char.strip()
print("\nReplace '-' with ' ' character in the said array of string values:")
print(np.char.strip(np.char.replace(str1, '-', ' '))) 

Sample Output:

Original array of string values:
[['Python-NumPy-Exercises']
 ['-Python-']]

Replace '-' with '=' character in the said array of string values:
[['Python==NumPy==Exercises']
 ['==Python==']]

Replace '-' with ' ' character in the said array of string values:
[['Python NumPy Exercises']
 ['Python']]

Explanation:

In the above code –

str1 = np.array([['Python-NumPy-Exercises'], ['-Python-']]): This creates a NumPy array str1 containing two strings. The first string is 'Python-NumPy-Exercises' and the second is '-Python-'. Each string is contained within its own array.

np.char.strip(np.char.replace(str1, '-', '==')): This line replaces all occurrences of '-' in the strings of str1 with '==' and then strips leading and trailing whitespace from each resulting string.

np.char.strip(np.char.replace(str1, '-', ' ')): This line replaces all occurrences of '-' in the strings of str1 with a space and then strips leading and trailing whitespace from each resulting string.

Python-Numpy Code Editor: