Parameters
The startswith() method accepts three parameters, one required & two optional. Let's discuss each parameter in more detail:
1. substring (required)
- This parameter specifies the substring to search for at the beginning of the string.
- It can be a single character or a longer substring.
- The search is case-sensitive, meaning "Hello" & "hello" are considered different substrings.
2. start (optional)
- This parameter specifies the position in the string where the search should start.
- It is an integer value representing the index of the character from where the search begins.
- By default, if not provided, the search starts from the beginning of the string (index 0).
- If start is greater than the length of the string, the method returns False.
3. end (optional)
- This parameter specifies the position in the string where the search should end.
- It is an integer value representing the index of the character where the search stops (exclusive).
- By default, if not provided, the search continues until the end of the string.
- If end is greater than the length of the string, the search still continues until the end of the string.
For example :
Python
text = "Hello, world!"
result1 = text.startswith("world", 7)
print(result1)
result2 = text.startswith("world", 0, 5)
print(result2)

You can also try this code with Online Python Compiler
Run Code
Output
True
False
In the first example, we check if the substring "world" appears at index 7 in the string "Hello, world!". Since "world" indeed starts at index 7, the method returns True.
In the second example, we check if the substring "world" appears within the range of index 0 to 5 (exclusive) in the string "Hello, world!". Since "world" is not present within that range, the method returns False.
Return
The startswith() method returns a boolean value indicating whether the string starts with the specified substring or not. There are two possible return values:
1. True: If the string starts with the specified substring, the method returns True.
2. False: If the string does not start with the specified substring, the method returns False.
Here are a few examples to show the return values:
Python
text1 = "Python is easy to learn."
result1 = text1.startswith("Python")
print(result1)
text2 = "Python is easy to learn."
result2 = text2.startswith("Java")
print(result2)
text3 = "Python is easy to learn."
result3 = text3.startswith("is", 7)
print(result3)
text4 = "Python is easy to learn."
result4 = text4.startswith("easy", 0, 6)
print(result)

You can also try this code with Online Python Compiler
Run Code
Output
True
False
True
False
In the first example, the string "Python is easy to learn." starts with the substring "Python", so the method returns True.
In the second example, the string does not start with the substring "Java", so the method returns False.
In the third example, we specify the start parameter as 7, & the substring "is" indeed appears at index 7 in the string, so the method returns True.
In the fourth example, we specify the start parameter as 0 & the end parameter as 6. The substring "easy" is not present within the range of index 0 to 6 (exclusive), so the method returns False.
The return value of the startswith() method allows you to make decisions or perform actions based on whether a string starts with a specific substring or not.
String startswith() in Python Example
Let’s look at few more examples to understand different scenarios :
Example 1: Checking for a prefix
Python
fruits = ["apple", "banana", "cherry", "date"]
for fruit in fruits:
if fruit.startswith("a"):
print(fruit)

You can also try this code with Online Python Compiler
Run Code
Output
apple
In this example, we have a list of fruits & we want to print only the fruits that start with the letter "a". We use the startswith() method inside a loop to check each fruit. If a fruit starts with "a", it is printed.
Example 2: Checking for multiple substrings
Python
text = "The quick brown fox jumps over the lazy dog."
if text.startswith(("The", "A", "An")):
print("The string starts with 'The', 'A', or 'An'.")
else:
print("The string does not start with 'The', 'A', or 'An'.")

You can also try this code with Online Python Compiler
Run Code
Output
The string starts with 'The', 'A', or 'An'.
In this example, we want to check if the string starts with any of the substrings "The", "A", or "An". We pass a tuple of substrings to the startswith() method. If the string starts with any of these substrings, the method returns True & the corresponding message is printed.
Example 3: Checking within a range
Python
url = "https://www.codingninjas.com"
if url.startswith("https", 0, 5):
print("The URL uses HTTPS protocol.")
else:
print("The URL does not use HTTPS protocol.")

You can also try this code with Online Python Compiler
Run Code
Output
The URL uses HTTPS protocol.
In this example, we have a URL & we want to check if it uses the HTTPS protocol. We use the startswith() method with the start & end parameters to check if the substring "https" appears within the range of index 0 to 5 (exclusive). If it does, the method returns True & the corresponding message is printed.
Python startswith() Without start and end Parameters
When using the startswith() method without the start and end parameters, it checks if the string starts with the specified substring from the beginning of the string.
Example 1
Python
message = "Hello, how are you?"
print(message.startswith("Hello"))
print(message.startswith("hello"))
print(message.startswith("how"))

You can also try this code with Online Python Compiler
Run Code
Output
True
False
False
In this example, we have a string "Hello, how are you?". We use the startswith() method to check if the string starts with different substrings.
- In the first case, the method returns True because the string indeed starts with "Hello".
- In the second case, the method returns False because the string does not start with "hello" (case-sensitive).
- In the third case, the method returns False because the string does not start with "how".
Example 2
Python
filename = "document.txt"
if filename.startswith("document"):
print("The file is a document.")
else:
print("The file is not a document.")

You can also try this code with Online Python Compiler
Run Code
Output
The file is a document.
In this example, we have a filename "document.txt". We use the startswith() method to check if the filename starts with the substring "document". Since it does, the method returns True, and the corresponding message is printed.
When the start and end parameters are not provided, the startswith() method checks for the substring at the beginning of the string by default. It is a simpler and more commonly used form of the method when you only need to check for a prefix or a substring at the start of the string.
Python startswith() With start and end Parameters
The startswith() method also allows you to specify the start and end parameters to check for a substring within a specific range of the string.
Example 1
Python
text = "Python is easy to learn."
print(text.startswith("is", 7))
print(text.startswith("is", 0, 7))
print(text.startswith("easy", 10))
print(text.startswith("easy", 10, 14))

You can also try this code with Online Python Compiler
Run Code
Output
True
False
True
True
In this example, we have the string "Python is easy to learn.". We use the startswith() method with different start and end parameters.
- In the first case, we check if the substring "is" appears at index 7. The method returns True because "is" indeed starts at index 7.
- In the second case, we check if the substring "is" appears within the range of index 0 to 7 (exclusive). The method returns False because "is" is not present in that range.
- In the third case, we check if the substring "easy" appears starting from index 10. The method returns True because "easy" starts at index 10.
- In the fourth case, we check if the substring "easy" appears within the range of index 10 to 14 (exclusive). The method returns True because "easy" is present in that range.
Example 2
Python
numbers = "123456789"
print(numbers.startswith("345", 2))
print(numbers.startswith("345", 2, 5))
print(numbers.startswith("789", 6))
print(numbers.startswith("789", 6, 9))

You can also try this code with Online Python Compiler
Run Code
Output
True
True
True
True
In this example, we have a string of numbers "123456789". We use the startswith() method with start and end parameters to check for substrings within specific ranges.
- In the first case, we check if the substring "345" appears starting from index 2. The method returns True because "345" indeed starts at index 2.
- In the second case, we check if the substring "345" appears within the range of index 2 to 5 (exclusive). The method returns True because "345" is present in that range.
- In the third case, we check if the substring "789" appears starting from index 6. The method returns True because "789" starts at index 6.
- In the fourth case, we check if the substring "789" appears within the range of index 6 to 9 (exclusive). The method returns True because "789" is present in that range.
Check if a String Starts with a Substring:
One common use case of the startswith() method is to check if a string starts with a specific substring. This can be helpful when you need to filter or categorize strings based on certain prefixes or patterns.
Example 1: Filtering strings based on a prefix
Python
names = ["Rahul", "Ravi", "Rinki", "Harsh", "Sanjana", "Sinki", "Mehak"]
r_names = [name for name in names if name.startswith("R")]
print(r_names)

You can also try this code with Online Python Compiler
Run Code
Output
['Rahul', 'Ravi', 'Rinki']
In this example, we have a list of names. We want to filter the names that start with the letter "R". We use a list comprehension along with the startswith() method to create a new list `r_names` containing only the names that start with "R".
Example 2: Categorizing strings based on a substring
Python
files = ["report.pdf", "presentation.ppt", "README.md", "image.jpg", "document.doc"]
docs = []
images = []
others = []
for file in files:
if file.startswith("report") or file.startswith("document"):
docs.append(file)
elif file.startswith("image"):
images.append(file)
else:
others.append(file)
print("Documents:", docs)
print("Images:", images)
print("Others:", others)

You can also try this code with Online Python Compiler
Run Code
Output
['report.pdf', 'document.doc']
['image.jpg']
['presentation.ppt', 'README.md']
In this example, we have a list of filenames. We want to categorize the files into three lists: `docs` for documents, `images` for image files, and `others` for the remaining files. We iterate over each file and use the startswith() method to check if the filename starts with specific substrings.
- If the filename starts with "report" or "document", it is appended to the `docs` list.
- If the filename starts with "image", it is appended to the `images` list.
- Otherwise, the file is appended to the `others` list.
Finally, we print the categorized lists.
Note: When we check if a string starts with a substring using the startswith() method, it allows us to make decisions or perform actions based on specific prefixes or patterns. It provides a convenient way to filter, categorize, or process strings based on their initial characters or substrings.
Frequently Asked Questions
Is the startswith() method case-sensitive?
Yes, the startswith() method is case-sensitive. It distinguishes between uppercase & lowercase letters.
Can the startswith() method check for multiple substrings at once?
Yes, you can pass a tuple of substrings to the startswith() method to check if the string starts with any of the specified substrings.
What happens if the start or end parameter is greater than the length of the string?
If the start parameter is greater than the length of the string, the method returns False. If the end parameter is greater than the length of the string, the search still continues until the end of the string.
Conclusion
In this article, we learned about the startswith() method in Python, which allows us to check if a string starts with a specified substring. We discussed it’s syntax, parameters, & return values. We also looked at different examples of using the method with & without the start & end parameters. The startswith() method is a useful tool for checking prefixes, filtering strings, & categorizing data based on initial substrings.