使用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 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告