NumPy: Replace "PHP" with "Python" in the element of a given array
NumPy String: Exercise-13 with Solution
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:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a NumPy program to make all the elements of a given string a numeric string of 5 digits with zeros on its left.
Next: Write a NumPy program to test equal, not equal, greater equal, greater and less test of all the elements of two given arrays.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://198.211.115.131/python-exercises/numpy/python-numpy-string-exercise-13.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics