📜  Python字符串 find() 方法

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

Python字符串 find() 方法

如果在给定字符串中找到子字符串,则Python String find() 方法返回子字符串的最低索引。如果未找到,则返回 -1。

示例 1:没有开始和结束参数的 find()

Python3
word = 'geeks for geeks'
  
# returns first occurrence of Substring
result = word.find('geeks')
print ("Substring 'geeks' found at index:", result )
  
result = word.find('for')
print ("Substring 'for ' found at index:", result )
  
# How to use find()
if (word.find('pawan') != -1):
    print ("Contains given substring ")
else:
    print ("Doesn't contains given substring")


Python3
word = 'geeks for geeks'
  
# Substring is searched in 'eks for geeks' 
print(word.find('ge', 2)) 
  
# Substring is searched in 'eks for geeks' 
print(word.find('geeks ', 2)) 
  
# Substring is searched in 's for g' 
print(word.find('g', 4, 10)) 
  
# Substring is searched in 's for g' 
print(word.find('for ', 4, 11))


输出:

Substring 'geeks' found at index: 0
Substring 'for ' found at index: 6
Doesn't contains given substring

示例 2:带有 start 和 end 参数的 find()

Python3

word = 'geeks for geeks'
  
# Substring is searched in 'eks for geeks' 
print(word.find('ge', 2)) 
  
# Substring is searched in 'eks for geeks' 
print(word.find('geeks ', 2)) 
  
# Substring is searched in 's for g' 
print(word.find('g', 4, 10)) 
  
# Substring is searched in 's for g' 
print(word.find('for ', 4, 11))

输出:  

10
-1
-1
6