Python startswith

Python startswith 方法在字符串以指定子字符串开头时返回布尔值 TRUE,否则返回 False。startswith 函数在我们需要检查用户输入的开头词时非常有用。

Python 字符串 startswith 方法的语法是:

String_Value.StartsWith(Substring, Starting_Position, Ending_Position)
  • String_Value:一个有效的字面量。
  • Substring:要搜索的字符串,如果找到,则此方法返回 true。
  • Starting_Position (可选):如果要指定起始点(开始索引位置),请在此处指定索引值。如果省略,startswith 函数将零视为起始位置。
  • Ending_Position (可选):在此处指定端点(搜索的结束索引位置)。如果省略,它将最高数字视为结束。

Python startswith 函数示例

以下示例集可帮助您了解 startswith 函数。

在用示例文本声明 Str1 后,第一个字符串函数语句使用它检查字符串 Str1 是否以“Learn”开头。

Python startswith 函数允许我们使用开始索引位置。通过指定开始索引位置,我们可以从给定字符串的中间开始检查。对于 Str5,我们将六作为起始点。

字符串 startswith 还允许使用开始和结束参数。通过指定开始和结束索引位置,我们可以提高性能。对于 Str6,它检查索引位置 6 是否以给定的子字符串开头。

如果字符串 startswith 在起始点未找到指定的字符串,则返回布尔值 False。此 Str7 语句返回 False,因为此Python函数从 7 开始查找(表示跳过“Python”一词),并在索引位置 21 结束。我们都知道,子字符串在位置 6。

Str1 = 'Learn Python at Tutorial Gateway';
Str2 = Str1.startswith('Learn')
print('First Output of method is = ', Str2)

# Performing function directly
Str3 = 'Find Tutorial at Tutorial Gateway'.startswith('Find')
print('Second Output is = ', Str3)

# Using First Index while finding
Str5 = Str1.startswith('Python', 6)
print('Third Output  is = ', Str5)

# Using First & Second Index while finding
Str6 = Str1.startswith('Python', 6, len(Str1) -1)
print('Fourth Output is = ', Str6)

# Using First & Second Index while finding Non existing
Str7 = Str1.startswith('Python', 7, 21)
print('Fifth Output is = ', Str7)
StartsWith Function Example