w3resource

NumPy: Insert a space between characters of all the elements of a given array


Write a NumPy program to insert a space between characters of all the elements of a given array.

Sample Solution:-

Python Code:

# Importing necessary library
import numpy as np

# Creating a NumPy array containing strings
x = np.array(['python exercises', 'PHP', 'java', 'C++'], dtype=np.str)

# Displaying the original array
print("Original Array:")
print(x)

# Using np.char.join to join elements of the array with a space character
r = np.char.join(" ", x)

# Displaying the result after joining elements with a space
print(r) 

Sample Input:

(['python exercises', 'PHP', 'java', 'C++'], dtype=np.str)

Sample Output:

Original Array:
['python exercises' 'PHP' 'java' 'C++']
['p y t h o n   e x e r c i s e s' 'P H P' 'j a v a' 'C + +']

Explanation:

In the above exercise –

x1 = np.array(['python exercises', '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 exercises ', 'PHP', 'Java', and 'C++'.

r = np.char.join(" ", x):

In the above code –

  • The np.char.join() method takes two arguments:
  • The first argument is the string to be used as a separator while joining the elements of the input array.
  • The second argument is the array of strings to be joined.
  • In this case, the separator used is a space character (" ") and the array of strings to be joined is 'x'.
  • The resulting string after joining the elements of the input array is stored in the variable 'r'.

Pictorial Presentation:

NumPy String: Insert a space between characters of all the elements of a given array

Python-Numpy Code Editor: