Python startswith

Python startswith method returns Boolean TRUE if the string starts with the specified substring; otherwise, it returns False. The startswith Function is handy when we want to check the starting term of user input.

The syntax of the Python string startswith method is

String_Value.StartsWith(Substring, Starting_Position, Ending_Position)
  • String_Value: A valid literal.
  • Substring: String you want to search, and if it finds, this method returns true.
  • Starting_Position (Optional): If you want to specify the starting point (beginning index position), then please specify the index value here. If you omit, the Python startswith Function considers Zero as a beginning position.
  • Ending_Position (Optional): Specify the endpoint (Ending index position of the search) here. If you omit, it considers the highest number as the end.

Python startswith function Example

The following set of examples help you understand the Python startswith Function.

After declaring Str1 with sample text, the first String function statement checks whether the string Str1 started with the term ‘Learn’ or not using it.

The Python startswith function allows us to use the Start index position. By specifying the starting index position, we can start checking from the middle of a given string. For Str5, we used six as the beginning point.

The string startswith also allows using of Start and end parameters. By specifying both the starting and ending index positions, we can increase the performance. For Str6, it checks whether the index position 6 is beginning with the given substring or not.

If the string startswith in Python does not find the specified string at the starting point, it returns Boolean False. This Str7 statement returns False because this Python function begin looking from 7 (it means term ‘Python’ is skipped) and ends at index position 21. As we all know, the substring is in position 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)
Python StartsWith