📜  Python字符串 index() 方法

📅  最后修改于: 2022-05-13 01:55:30.439000             🧑  作者: Mango

Python字符串 index() 方法

在字符串中查找字符串(子字符串)是一个在日常生活中有很多用途的应用程序。 Python使用函数index() 提供此功能,该函数返回子字符串在字符串中第一次出现的位置。

示例 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)


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)


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 first position of geeks after 2nd index : 8

示例 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