NumPy join()函数

原文:https://www.studytonight.com/numpy/numpy-join-function

在本教程中,我们将介绍 Python 中 Numpy 库的 char 模块中的join()函数。

join()函数用于向任意给定字符串或给定字符串数组的所有元素添加分隔符或字符串。举个简单的例子,如果你有一个字符串“ STUDY ”,你想用“ - ”作为分隔符,那么使用join()函数输出的将是“ S-T-U-D-Y ”。

这个函数基本上在数组的每个元素内部调用str.join函数。

numpy.char.join()的语法:

使用该函数所需的语法如下:

numpy.char.join(sep, seq)

以上语法表明join()函数取两个参数。

参数:

现在让我们看看这个函数的参数:

  • sep 这个参数代表一个用作分隔符的字符串/字符数组。

  • seq 此参数指示将对其执行操作的输入数组或字符串。

返回值:

此函数返回带有连接元素的字符串或 Unicode 输出数组。

示例 1:使用简单的字符串

该函数的基本示例如下:

import numpy as np

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

输出中的连接字符串: D:G

示例 2:使用字符串数组

在下面的代码片段中,我们将对字符串数组使用join()函数,该函数对数组中的每个字符串元素使用唯一的搜索符。

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)

原始输入数组: [' apple ' ' python ' ' numpy ' ' study now '] 输出连接数组:【'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 ']

示例 3:使用分隔符字符串

在这个代码示例中,我们将对给定数组的所有字符串元素使用单个分隔符字符串。

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)

原始输入数组: [“apple”“python”“numpy”“study now”] 输出连接数组:【'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'】

摘要

在本教程中,我们介绍了 Numpy 库的join()函数,该函数用于通过提供分隔符或字符串向任何字符串或字符串数组的所有元素添加分隔符。