Python 字符串查找

Python 字符串的 find 函数用于返回指定字符串第一次出现的索引位置。如果找不到指定的字符串,则返回 -1。在本节中,我们将通过一个示例讨论如何编写一个 find 字符串函数。此方法中的索引位置从 0 开始,而不是 1。

Python 编程语言中字符串 find 函数的语法如下所示。

String_Value.find(Substring, Starting_Position, Ending_Position)
  • String_Value:有效字面量。
  • 要搜索的子字符串。
  • Starting_Position(可选):如果要指定起始点(起始索引位置),请在此处指定值。如果省略此参数,则 find 函数将零视为起始位置。
  • Ending_Position(可选):如果要指定终点(结束索引位置),请在此处指定值。如果省略此参数,则 find 函数将考虑最大数字。

如何在 Python 中查找字符串中的子字符串?

以下示例集可帮助您理解 find 字符串。在第一个语句中,Str2 使用 find 方法在 Str1 中查找子字符串“abc”的所有出现,并打印输出。

如果函数在 Str1 中找不到指定的子字符串,则返回 -1。我们使用 Str4 来解释这一点。

Python 字符串 find 函数允许我们使用子字符串的起始索引位置。通过将 Str5 的起始索引位置指定为 12,我们可以提高性能。

它允许我们使用起始和结束索引。通过提供起始和结束索引位置,我们可以提高性能。以下 Str6 Python 语句开始在位置 12 查找“abc”。

最后一行 Str7 返回 -1,因为此字符串 find 函数从 12 开始查找(这意味着第一个 abc 被跳过),并在索引位置 21 结束。众所周知,第二个 abc 的位置是 22。

Str1 = 'We are abc working at abc company';
Str2 = Str1.find('abc')
print('First Output of a method is = ', Str2)

# Performing directly
Str3 = 'Get Tutorial at Tutorial Gateway'.find('Tutorial')
print('Second Output of a method is = ', Str3)

# Searching for Not existing Item
Str4 = Str1.find('Tutorial')
print('Third Output = ', Str4)

# Using First Index
Str5 = Str1.find('abc', 12)
print('Fourth Output = ', Str5)

# Using First & Second
Str6 = Str1.find('abc', 12, len(Str1) -1)
print('Fifth Output = ', Str6)

# Using First & Second while looking at Non existing one
Str7 = Str1.find('abc', 12, 21)
print('Sixth Output of this method is = ', Str7)
Find string function