NumPy: Replace "PHP" with "Python" in the element of a given array
Write a NumPy program to replace "PHP" with "Python" in the element of a given array.
Sample Solution:
Python Code:
# Importing necessary library
import numpy as np
# Creating a NumPy array containing a single string
x = np.array(['PHP Exercises, Practice, Solution'], dtype=np.str)
# Displaying the original array
print("\nOriginal Array:")
print(x)
# Replacing "PHP" with "Python" in the string of the array
r = np.char.replace(x, "PHP", "Python")
# Displaying the updated array after replacing the substring
print("\nNew array:")
print(r)
Sample Input:
(['PHP Exercises, Practice, Solution'], dtype=np.str)
Sample Output:
Original Array: ['PHP Exercises, Practice, Solution'] New array: ['Python Exercises, Practice, Solution']
Explanation:
In the above exercise –
x = np.array(['PHP Exercises, Practice, Solution'], dtype=np.str): This line creates a NumPy array x is created, which contains a single string element.
r = np.char.replace(x, "PHP", "Python"): In the above code replace() function is called, which takes three arguments:
- The first argument is the array of strings to operate on, in this case, x.
- The second argument is the substring to be replaced, in this case, "PHP".
- The third argument is the new substring to replace the old substring, in this case, "Python".
The replace() function returns a new NumPy array r with the same shape and data type as x, but with the specified replacements made. The output of the new array is ['Python Exercises, Practice, Solution'].
Pictorial Presentation:
Python-Numpy Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics