NumPy center()
功能
在本教程中,我们将介绍 Numpy 库中 char 模块的center()
功能。
center()
功能用于返回所需宽度的输入数组的副本,以便字符串的输入数组居中并用 fillchar 进行左右填充。
- 简单来说,这个函数从输入字符串中创建并返回一个新字符串,这个新字符串是,在左侧和右侧都填充了指定的字符。
- 这个函数基本上对数组的每个元素都调用
str.center
。
numpy.char.center()
的语法:
使用该函数所需的语法如下:
numpy.char.center(a, width, fillchar=' ')
以上语法表明center()
函数取两个参数。
参数:
现在让我们看看这个函数的参数:
a 该参数表示将应用函数的字符串或字符串数组。
宽度 该参数表示结果字符串的长度。
填充字符 该参数表示要用作填充符的填充字符,该参数的默认值为空格。
返回值:
这个函数返回一个用指定字符填充的新字符串。
示例 1:使用字符串
代码片段如下,我们将使用带有简单字符串的center()
函数:
import numpy as np
a1 = "StudyTonight!"
print("Padding the Inut string through left and right with the fill char ^:");
x = np.char.center(a1, 30, '^')
print(x)
用填充字符^: ^^^^^^^^StudyTonight 填充 Inut 字符串的左右两端!^^^^^^^^^
示例 2:使用字符串数组
在下面的代码中,我们将对字符串数组使用center()
函数。这个函数对数组中的每个字符串元素都以相同的方式起作用,就像它对上面例子中的单个字符串所做的那样。
import numpy as np
arr= np.array(['StudyTonight', 'Online', 'Portal'])
print("The Original Array :")
print(arr)
output = np.char.center(arr, 30, '^')
print("\nThe Resultant array :")
print(output)
原阵: 【【StudyTonight】【上线】【传送门】】
合阵: 【'^^^^^^^^^studytonight^^^^^^^^^' '^^^^^^^^^^^^online^^^^^^^^^^^^' '^^^^^^^^^^^^portal^^^^^^^^^^^^'】
摘要
在本教程中,我们介绍了用于向数组中的字符串或字符串元素添加填充的center()
函数。我们介绍了两个不同的代码示例,展示了针对单个字符串和字符串数组的center()
函数。