How to insert a space between characters of all the elements of a given NumPy array?

In this article, we will discuss how to insert a space between the characters of all elements of a given array of string. 
Example:

Suppose we have an array of string as follows:
A = ["Beginner", "for", "Beginner"]

then when we insert a space between the characters
of all elements of the above array we get the 
following output.
A = ["g e e k s", "f o r", "g e e k s"]

To do this we will use np.char.join(). This method basically returns a string in which the individual characters are joined by separator character that is specified in the method. Here the separator character used is space. 

Syntax: np.char.join(sep, string) 

Parameters:
sep: is any specified separator 
string: is any specified string. 

Example:

Python3




# importing numpy as np
import numpy as np
  
  
# creating array of string
x = np.array(["Beginner", "for", "Beginner"],
             dtype=np.str)
print("Printing the Original Array:")
print(x)
  
# inserting space using np.char.join()
r = np.char.join(" ", x)
print("Printing the array after inserting space\
between the elements")
print(r)


Output:

Printing the Original Array:
['Beginner' 'for' 'Beginner']
Printing the array after inserting spacebetween the elements
['g e e k s' 'f o r' 'g e e k s']

Contact Us