Python 字符串 find()

find() 方法返回子字符串第一次出现的索引(如果找到)。如果未找到,则返回 -1

示例

message = 'Python is a fun programming language'

# check the index of 'fun' print(message.find('fun'))
# Output: 12

find() 语法

find() 方法的语法是

str.find(sub[, start[, end]] )

find() 参数

find() 方法最多接受三个参数

  • sub - 要在 str 字符串 中搜索的子字符串。
  • startend(可选)- 搜索子字符串的范围 str[start:end]

find() 返回值

find() 方法返回一个整数值

  • 如果子字符串存在于字符串中,则返回子字符串第一次出现的索引。
  • 如果子字符串不存在于字符串中,则返回 -1

find() 方法的工作原理

How find() and rfind() works in Python?
Python 字符串的 find() 和 rfind() 方法的工作原理

示例 1:不带 start 和 end 参数的 find()

quote = 'Let it be, let it be, let it be'

# first occurance of 'let it'(case sensitive)
result = quote.find('let it')
print("Substring 'let it':", result) # find returns -1 if substring not found
result = quote.find('small')
print("Substring 'small ':", result) # How to use find()
if (quote.find('be,') != -1):
print("Contains substring 'be,'") else: print("Doesn't contain substring")

输出

Substring 'let it': 11
Substring 'small ': -1
Contains substring 'be,'

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

quote = 'Do small things with great love'

# Substring is searched in 'hings with great love'
print(quote.find('small things', 10))
# Substring is searched in ' small things with great love' print(quote.find('small things', 2)) # Substring is searched in 'hings with great lov'
print(quote.find('o small ', 10, -1))
# Substring is searched in 'll things with' print(quote.find('things ', 6, 20))

输出

-1
3
-1
9

另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战