w3resource

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

NumPy String: Exercise-20 with Solution

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:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a NumPy program to add two zeros to the beginning of each element of a given array of string values.
Next: Write a NumPy program to count a given word in each row of a given array of string values.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.