使用Python的index()方法查找字符串中子字符串出现的最低索引


使用Python Numpy中的numpy.char.index()方法查找字符串中子字符串sub出现的最低索引。该方法返回整数类型的输出数组。如果找不到sub,则会引发ValueError异常。第一个参数是输入数组,第二个参数是要搜索的子字符串。

步骤

首先,导入所需的库:

import numpy as np

创建一个一维字符串数组:

arr = np.array(['KATIE', 'KATE'])

显示我们的数组:

print("Array...\n",arr)

获取数据类型:

print("\nArray datatype...\n",arr.dtype)

获取数组的维度:

print("\nArray Dimensions...\n",arr.ndim)

获取数组的形状:

print("\nOur Array Shape...\n",arr.shape)

获取数组的元素个数:

print("\nNumber of elements in the Array...\n",arr.size)

使用numpy.char.index()方法查找字符串中子字符串sub出现的最低索引:

print("\nResult (index() method)...\n",np.char.index(arr, 'AT'))

示例

import numpy as np

# Create a One-Dimensional array of strings
arr = np.array(['KATIE', 'KATE'])

# Displaying our array
print("Array...\n",arr)

# Get the datatype
print("\nArray datatype...\n",arr.dtype)

# Get the dimensions of the Array
print("\nArray Dimensions...\n",arr.ndim)

# Get the shape of the Array
print("\nOur Array Shape...\n",arr.shape)

# Get the number of elements of the Array
print("\nNumber of elements in the Array...\n",arr.size)

# Return the lowest index in the string where substring sub is found using the numpy.char.index() method in Python Numpy
print("\nResult (index() method)...\n",np.char.index(arr, 'AT'))

输出

Array...
['KATIE' 'KATE']

Array datatype...
<U5

Array Dimensions...
1

Our Array Shape...
(2,)

Number of elements in the Array...
2

Result (index() method)...
[1 1]

更新于:2022年2月25日

243 次浏览

开启你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.