NumPy: Repeat all the elements three times of a given array of string
NumPy String: Exercise-2 with Solution
Write a NumPy program to repeat all the elements three times of a given array of string.
Sample Solution:
Python Code:
# Importing the necessary library
import numpy as np
# Creating a NumPy array containing strings
x1 = np.array(['Python', 'PHP', 'Java', 'C++'], dtype=np.str)
# Displaying the original array
print("Original Array:")
print(x1)
# Using np.char.multiply to repeat each string element in x1 three times
new_array = np.char.multiply(x1, 3)
# Displaying the new array with each string element repeated three times
print("New array:")
print(new_array)
Sample Input:
(['Python', 'PHP', 'Java', 'C++'], dtype=np.str)
Sample Output:
Original Array: ['Python' 'PHP' 'Java' 'C++'] New array: ['PythonPythonPython' 'PHPPHPPHP' 'JavaJavaJava' 'C++C++C++']
Explanation:
In the above exercise –
x1 = np.array(['Python', 'PHP', 'Java', 'C++'], dtype=np.str): This line creates a 1-dimensional numpy array x1 with 4 elements of string data type. The elements are 'Python', 'PHP', 'Java', and 'C++'.
new_array = np.char.multiply(x1, 3): This line applies the np.char.multiply() function to the x1 array with a value of 3. The np.char.multiply() function is used to replicate the elements of the input array. In this case, each string element of x1 is repeated 3 times, and the resulting new array is stored in the variable new_array.
Finally print() function print the content of new_array and output will be - ['PythonPythonPython' 'PHPPHPPHP' 'JavaJavaJava' 'C++C++C++']
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 concatenate element-wise two arrays of string.
Next: Write a NumPy program to capitalize the first letter, lowercase, uppercase, swapcase, title-case of all the elements of a given array.
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://www.w3resource.com/python-exercises/numpy/python-numpy-string-exercise-2.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics