startswith(): Check string begins with a specified substring

main_string.startswith(search_string, start, end)
Returns True if the main string starts with specified search string, otherwise returns False
search_string
Required, String to be searched to check to match starting of the main string.
start
Optional, Starting position of search , by default it is from 0 or starting position of string
end
Optional , ending position of search, by default it is end of the string.
This is case sensitive search.
my_str='Welcome to plus2net.com Python section'output=my_str.startswith('Wel') print(output) # output is Truemy_str='Welcome to plus2net.com Python section'output=my_str.startswith('co',3)print(output) # output is True
my_str='Welcome to plus2net.com Python section'output=my_str.startswith('co',20,24)print(output) # output is True
Output is here
TrueTrueTrue

Example 1: Basic Usage of startswith()

my_str = "Welcome to plus2net"print(my_str.startswith("Welcome"))  # Output: True

Example 2: Using start Parameter

Check if substring exists starting from a specific index.
my_str = "Python programming"print(my_str.startswith("pro", 7))   # Output: True

Example 3: Using start and end Parameters

Using both start and end to limit the search range.
text = "Data Science and Machine Learning"print(text.startswith("Science", 5, 15))  # Output: True

Applications of startswith()

  • Data Parsing: Filter text data that starts with specific characters or keywords.
  • URL Validation: Check if a URL starts with "http" or "https".
  • File Format Verification: Identify specific file types or prefixes.

All String methods