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:

import numpy as np
x1 = np.array(['Python', 'PHP', 'Java', 'C++'], dtype=np.str)
print("Original Array:")
new_array = np.char.multiply(x1, 3)
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++']


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:

NumPy String: Repeat all the elements three times of a given array of 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 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.

Follow us on Facebook and Twitter for latest update.

Python: Tips of the Day

Memory Footprint Of An Object:

import sys 
x = 'farhadmalik'


We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook