Signup/Sign In

NumPy join() function

In this tutorial, we will cover join() function in the char module of the Numpy Library in Python.

The join() function is used to add a separator character or string to any given string or to all the elements of the given array of strings. Let's take a simple example, if you have a string "STUDY" and you want to use "-" as separator character, then using the join() function the output will be "S-T-U-D-Y".

This function basically calls str.join function internally on every element of the array.

Syntax of numpy.char.join():

The syntax required to use this function is as follows:

numpy.char.join(sep, seq)

The above syntax indicates that join() function takes two parameters.

Parameters:

Let us now take a look at the parameters of this function:

  • sep
    This argument represents an array of string/characters used as the separator characters.

  • seq
    This argument indicates the input array or string on which the operation will be performed.

Returned Values:

This function returns an output array of either string or Unicode with the joined elements.

Example 1: With a simple string

The basic example of this function is as follows:

import numpy as np
   
a = np.char.join(':','DG')
print("The Joined string in the output:")
print(a)


The Joined string in the output:
D:G

Example 2: With an Array of String

In the below code snippet we will use join() function on the array of strings with unique searator for each string element of the array.

import numpy as np

inp = np.array(['Apple', 'Python', 'NumPy','StudyTonight']) 
print ("The original Input array : \n", inp) 

sep = np.array(['^', '+', '*','-']) 

output= np.char.join(sep, inp) 
print ("The Output joined array: ", output) 


The original Input array :
['Apple' 'Python' 'NumPy' 'StudyTonight']
The Output joined array: ['A^p^p^l^e' 'P+y+t+h+o+n' 'N*u*m*P*y' 'S-t-u-d-y-T-o-n-i-g-h-t']

Example 3: Using a separator String

In this code example, we will use a single separator string for all the string elements of the given array.

import numpy as np

inp = np.array(['Apple', 'Python', 'NumPy','StudyTonight']) 
print ("The original Input array : \n", inp) 

sep = np.array(['^^^']) 

output= np.char.join(sep, inp) 
print ("The Output joined array: ", output) 


The original Input array :
['Apple' 'Python' 'NumPy' 'StudyTonight']
The Output joined array: ['A^^^p^^^p^^^l^^^e' 'P^^^y^^^t^^^h^^^o^^^n' 'N^^^u^^^m^^^P^^^y'
'S^^^t^^^u^^^d^^^y^^^T^^^o^^^n^^^i^^^g^^^h^^^t']

Summary

In this tutorial we covered the join() function of the Numpy Library which is used to add a separator to any string or to all the elements of a string array by providing a separator character or string.



About the author:
Aspiring Software developer working as a content writer. I like computer related subjects like Computer Networks, Operating system, CAO, Database, and I am also learning Python.