﻿ NumPy: Repeat all the elements three times of a given array of string - w3resource

# 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:")
print(x1)
new_array = np.char.multiply(x1, 3)
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.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

﻿

## Python: Tips of the Day

Memory Footprint Of An Object:

```import sys
```60