在字符串中查找字符串(子字符串)是一個在 day-to-day 生活中有很多用途的應用程序。 Python 使用函數 index() 提供此函數,該函數返回子字符串在字符串中第一次出現的位置。
用法:
ch.index(ch1, begp, endp)
Parameters:
- ch1:要搜索的字符串。
- begp(默認值:0):此函數指定必須開始搜索的位置。
- endp(默認:string_len):此函數指定搜索必須結束的位置。
返回值:
返回找到的子字符串的第一個位置。
異常:
如果未找到參數字符串,則引發 ValueError。
例子1
Python
# Python code to demonstrate the working of
# index()
# initializing target string
ch = "geeksforgeeks"
# initializing argument string
ch1 = "geeks"
# using index() to find position of "geeks"
# starting from 2nd index
# prints 8
pos = ch.index(ch1,2)
print ("The first position of geeks after 2nd index:",end="")
print (pos)
輸出:
The first position of geeks after 2nd index:8
Note:The index() method is similar to find(). The only difference is find() returns -1 if the searched string is not found and index() throws an exception in this case.
示例 2:異常
ValueError:在目標字符串中找不到參數字符串的情況下會引發此錯誤。
Python
# Python code to demonstrate the exception of
# index()
# initializing target string
ch = "geeksforgeeks"
# initializing argument string
ch1 = "gfg"
# using index() to find position of "gfg"
# raises error
pos = ch.index(ch1)
print ("The first position of gfg is:",end="")
print (pos)
輸出:
Traceback (most recent call last): File "/home/aa5904420c1c3aa072ede56ead7e26ab.py", line 12, in pos = ch.index(ch1) ValueError:substring not found
例子3
實際應用:該函數用於提取目標詞前後的後綴或前綴長度。下麵的示例顯示來自字符串中給定信息的交流電壓指令的總位長。
Python
# Python code to demonstrate the application of
# index()
# initializing target strings
voltages = ["001101 AC", "0011100 DC", "0011100 AC", "001 DC"]
# initializing argument string
type = "AC"
# initializing bit-length calculator
sum_bits = 0
for i in voltages:
ch = i
if (ch[len(ch)-2]!='D'):
# extracts the length of bits in string
bit_len = ch.index(type)-1
# adds to total
sum_bits = sum_bits + bit_len
print ("The total bit length of AC is:",end="")
print (sum_bits)
輸出:
The total bit length of AC is:13
相關用法
- Python SymPy Permutation.index()用法及代碼示例
- Numpy string index()用法及代碼示例
- Python Pandas Index.insert()用法及代碼示例
- Python Pandas Index.get_slice_bound()用法及代碼示例
- Python Pandas Index.delete()用法及代碼示例
- Python Pandas Index.drop_duplicates()用法及代碼示例
- Python Pandas Series.str.index()用法及代碼示例
- Python Pandas Index.dropna()用法及代碼示例
- Python Pandas Index.contains()用法及代碼示例
- Python Pandas Series.nonzero()用法及代碼示例
- Python numpy.index()用法及代碼示例
注:本文由純淨天空篩選整理自manjeet_04大神的英文原創作品 Python String index() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。