Skip to content
Related Articles

Related Articles

Improve Article
Repeat all the elements of a NumPy array of strings
  • Last Updated : 02 Sep, 2020

Let us see how to repeat all elements of the given array of string 3 times.

Example :

Input : [‘Akash’, ‘Rohit’, ‘Ayush’, ‘Dhruv’, ‘Radhika’]
Output : [‘AkashAkashAkash’, ‘RohitRohitRohit’, ‘AyushAyushAyush’, ‘DhruvDhruvDhruv’, ‘RadhikaRadhikaRadhika’]

We will be using the numpy.char.multiply(a, i) method for this task.

numpy.char.multiply(a, i)

Syntax : numpy.char.multiply(a, i)
Parameters :



  • a : array of str or unicode
  • i : number of times to be repeated

Returns : Array of strings

Example 1 : Repeating 3 times.




# importing the module
import numpy as np
  
# created array of strings
arr = np.array(['Akash', 'Rohit', 'Ayush'
                'Dhruv', 'Radhika'], dtype = np.str)
print("Original Array :")
print(arr)
  
# with the help of np.char.multiply()
# repeating the characters 3 times
new_array = np.char.multiply(arr, 3)
print("\nNew array :")
print(new_array)

Output :

Original Array :
[‘Akash’ ‘Rohit’ ‘Ayush’ ‘Dhruv’ ‘Radhika’]

New array :
[‘AkashAkashAkash’ ‘RohitRohitRohit’ ‘AyushAyushAyush’ ‘DhruvDhruvDhruv’ ‘RadhikaRadhikaRadhika’]

Example 2: Repeating 2 times.




# importing the module
import numpy as np
  
# created array of strings
arr = np.array(['Geeks', 'for', 'Geeks'])
print("Original Array :")
print(arr)
  
# with the help of np.char.multiply()
# repeating the characters 3 times
new_array = np.char.multiply(arr, 2)
print("\nNew array :")
print(new_array)

Output :

Original Array :
['Geeks' 'for' 'Geeks']

New array :
['GeeksGeeks' 'forfor' 'GeeksGeeks']

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course




My Personal Notes arrow_drop_up
Recommended Articles
Page :