NumPy: Replace "PHP" with "Python" in the element of a given array
13. Replace "PHP" with "Python" in Strings
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:
For more Practice: Solve these Related Problems:
- Create a function that replaces all occurrences of the substring "PHP" with "Python" in a string array using np.char.replace.
- Implement a solution that performs case-insensitive replacement of "php" with "Python."
- Test the replacement function on an array containing multiple occurrences of "PHP" within a single string.
- Chain the replacement with trimming operations to ensure no extra whitespace is introduced.
Go to:
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.
Python-Numpy Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.