使用Python的index()方法返回字符串中子字符串在指定范围内出现的最低索引
使用Python NumPy中的numpy.char.index()方法返回字符串中子字符串sub出现的最低索引。该方法返回整数类型的输出数组。如果找不到sub,则引发ValueError异常。第一个参数是输入数组,第二个参数是要搜索的子字符串。第三个和第四个参数是可选参数,其中start和end的解释与切片表示法相同。
步骤
首先,导入所需的库:
import numpy as np
创建一个一维字符串数组:
arr = np.array(['KATIE', 'KATE', 'CRATE'])
显示我们的数组:
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出现的最低索引。该方法返回整数类型的输出数组。如果找不到sub,则引发ValueError异常:
print("\nResult (index() method)...\n",np.char.index(arr, 'AT', start = 1, end= 4))
示例
import numpy as np # Create a One-Dimensional array of strings arr = np.array(['KATIE', 'KATE', 'CRATE']) # 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 # The method returns the output array of ints. Raises ValueError if sub is not found. print("\nResult (index() method)...\n",np.char.index(arr, 'AT', start = 1, end= 4))
输出
Array... ['KATIE' 'KATE' 'CRATE'] Array datatype... <U5 Array Dimensions... 1 Our Array Shape... (3,) Number of elements in the Array... 3 Result (index() method)... [1 1 2]
广告