使用 Python rindex() 在指定範圍內查詢子字串並在字串中返回其最高索引
使用 Python NumPy 中的 numpy.char.rindex() 方法返回字串中子字串 sub 出現的最高索引。該方法返回整數輸出陣列。如果未找到 sub,則引發 ValueError。第一個引數是輸入陣列。第二個引數是要搜尋的子字串。第三個和第四個引數是可選引數,其中 start 和 end 的解釋與切片表示法相同。
步驟
首先,匯入所需的庫 -
import numpy as np
建立一個一維字串陣列 -
arr = np.array(['KATIE', 'KATE', 'BRATleukATp'])
顯示我們的陣列 -
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.rindex() 方法返回字串中子字串 sub 出現的最高索引 -
print("\nResult (rindex() method)...\n",np.char.rindex(arr, 'AT', start = 1, end= 9))
示例
import numpy as np
# Create a One-Dimensional array of strings
arr = np.array(['KATIE', 'KATE', 'BRATleukATp'])
# 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 highest index in the string where substring sub is found using the numpy.char.rindex() method in Python Numpy
# The method returns the output array of ints. Raises ValueError if sub is not found.
print("\nResult (rindex() method)...\n",np.char.rindex(arr, 'AT', start = 1, end= 9))輸出
Array... ['KATIE' 'KATE' 'BRATleukATp'] Array datatype... <U11 Array Dimensions... 1 Our Array Shape... (3,) Number of elements in the Array... 3 Result (rindex() method)... [1 1 2]
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP