Python startswith

The 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, CSV data, filter log data, etc.

Python startswith() syntax

The syntax of the string startswith method is

String_Value.StartsWith(Substring, Start_Position, End_Position)

Parameters

  • String_Value: A valid literal against which we check for a substring.
  • Substring: The string you want to search, and if it is found, the startswith() method returns true. It can be a string or a tuple of strings.
  • Start_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 the beginning position.
  • End_Position (Optional): Specify the endpoint (Ending index position of the search) here. If you omit, it considers the highest number as the end.

Return Value

If the original string (string_value) starts with a given value (substring), the startswith() function returns True. If it does not, the method will return False.

When you pass a starting_position integer value greater than the original string length, the startswith() function returns False.

Python startswith function Example

The following set of examples helps you understand the startswith Function. After declaring Str1 with sample text, the first String function statement checks whether the string Str1 starts with the term ‘Learn’ or not.

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 the use of Start and end parameters. We can increase the performance by specifying both the starting and ending index positions. For Str6, it checks whether the index position 6 begins with the given substring or not.

If the string startswith does not find the specified string at the starting point, it returns Boolean False. The Str7 statement returns False because the Python startswith() function begins looking from 7 (meaning the 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 function Example

Python startswith() without start and end parameters

In the following statement, we use the startswith() function without the start_position and end_position parameters. It means the search operations start at the first position of the original string.

text = "Welcome all"
print(text.startswith("Welcome"))
True

NOTE: If you replace the word “Welcome” with any other word, the above code returns False.

Using the start parameter

In this example, we mention the starting position in the startswith() function. In the second print statement, the search operation begins at the 4th index position, and the word starts with UK.

text = "USA UK INDIA"
print(text.startswith("UK"))
print(text.startswith("UK", 4))
False
True

Python startswith() with start and end parameters

As we mentioned earlier, we can use the start_position and end_position parameters of the startswith() method to restrict the search operation.

The following code searches for the United inside the original string from the 4th index position and searches up to the 9th position (10 is not included). If it finds, it returns true.

text = "The United States"
print(text.startswith("United", 4, 10))
True

NOTE: If you change the starting index position to 3, 5, or the ending index position to 9 or 11, the above code returns False.

startswith() with a Tuple of strings prefix

In all the above examples, we used only a single substring for the search operations. However, the startswith() supports using a tuple of strings as the prefix to search for multiple substrings.

text = "The United States"
print(text.startswith(("The", "the", "United")))
True

Check if a string in a list starts with a substring

The following example demonstrates the use tuple of strings as the startswith() method prefix. Here, we declared a list of strings. The for loop in list comprehension iterates over the list of items. The startswith() function checks whether the string starts with U or I. If true, add that item to a new list.

countries = ["USA", "INDIA", "UK", "FRANCE", "GERMANY"  ]

c = [a for a in countries if a.startswith(("U", "I"))]
print(c)
['USA', 'INDIA', 'UK']

Real-time examples and FAQs of Python startswith

Validate https URLS

The if else statement with the startswith() method checks whether the URL starts with https (secured site).

url = "https://www.tutorialgateway.org"

if url.startswith("https://"):
    print("Secure URL")
else:
    print("Insecure URL")
Secure URL

Is the startswith() function case-sensitive?

Yes. The startswith() function is case-sensitive, and it considers a and A as different entries.

text = "New York"
print(text.startswith("new"))
print(text.startswith("New"))
False
True

TIP: Use upper(), lower(), or casefold() function to normalize the string before checking with the startswith() method.

Difference between startswith() method and in operator

  • startswith: This function checks whether the string starts with a given substring.
  • In operator: It checks whether the substring exists (at any position) in the original string.

To check the starting position, use the startswith(). Use in operator to find a string anywhere. The following program shows the difference.

text = "New York"
print(text.startswith("New"))
print("New" in text)
print(text.startswith("York"))
print("York" in text)
True
True
False
True