Python 3 – 字符串查找方法(find())

Python 3 – 字符串查找方法(find())

Python 3 是一种强大而灵活的编程语言,能够完成各种任务。Python 3 中的字符串查找方法 find(),能够帮助程序员轻松定位字符串中的特定内容。

什么是字符串查找方法?

字符串查找方法(find())是 Python 3 中用来定位子字符串在字符串中出现位置的一种方法。如果指定的子字符串出现在字符串中,该方法会返回它在字符串中的索引值;如果未找到,该方法会返回 -1。

find() 函数语法

Python 3 中的字符串查找方法 find() 的语法如下:

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

其中:

  • str:表示要搜索的字符串。
  • sub:表示要查找的子字符串。
  • start:表示开始查找的位置,默认为 0。
  • end:表示结束查找的位置,默认为字符串长度。

find() 函数示例

下面是一个简单的例子,展示如何使用 find() 方法查找子字符串:

text = "I love Python programming language!"
position = text.find("Python")
if position != -1:
    print("Python found at position:", position)
else:
    print("Python not found")

输出结果为:

Python found at position: 7

这段代码中,我们使用 text.find(“Python”) 来查找字符串中的 Python 子字符串。因为 Python 出现在字符串 text 中,所以该方法返回它在字符串中的索引位置 7。

指定开始查找和结束查找的位置

在上面的示例中,我们没有指定开始和结束查找的位置。默认情况下,查找范围是整个字符串。

如果我们只想在字符串的一部分中查找子字符串,可以使用 start 和 end 参数指定查找范围。下面是一个示例:

text = "I love Python programming language!"
position = text.find("Python", 10, 20)
if position != -1:
    print("Python found at position:", position)
else:
    print("Python not found")

输出结果为:

Python not found

在此示例中,我们使用位置 10 到位置 20 之间的子字符串查找 Python 子字符串。因为 Python 子字符串不在这个子字符串中,所以 find() 函数返回值为 -1。

字符串查找示例

下面是一个更复杂的示例,用于查找字符串中特定单词的出现次数:

text = "She sells sea shells by the sea shore, " \
       "The shells she sells are surely seashells, " \
       "So if she sells shells on the seashore, " \
       "I'm sure she sells seashore shells."
word = "shells"
count = 0
position = 0
while True:
    position = text.find(word, position)
    if position == -1:
        break
    count += 1
    position += len(word)
print("The word", word, "appeared", count, "times.")

输出结果为:

The word shells appeared 4 times.

在此示例中,我们使用了一个 while 循环,在每次运行中查找子字符串。我们还使用 position 变量来记录上一次查找结束的位置,以便下一次查找从该位置开始。

结论

Python 3 的字符串查找方法 find() 可以轻松定位字符串中的子字符串,非常方便。无论是查找特定单词的出现次数,还是查找特定字符的位置,该方法都可以胜任。希望这篇文章对你有所帮助!

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程