Understanding Python startswith() Function
In Python, The “startswith()” function belonging to the str class is utilized to verify whether a specific string starts with a given sequence of characters. If it does, this function will yield True; otherwise, it will return False.
In this article, we will discuss the startswith() function and understand its use with the help of examples. We will be covering the following sections:
- Introduction to Python startswith() Function
- Syntax
- Examples of Using the startswith() Function in Python
What is Python startswith() Function?
The Python startswith() function is a built-in method in Python that belongs to the “str” class. This function is used to check whether a string starts with a specific sequence of characters or not. The startswith() function takes one mandatory argument, which is the prefix string that we want to check whether the original string starts with.
Explore free Python courses
Best-suited Python courses for you
Learn Python with these high-rated online courses
Syntax of Python startswith()
The syntax of startswith() function in Python is given as:
string.startswith(prefix, start, end)
Parameters of startswith()
The startswith() method in Python accepts three parameters:
- “string”: The string or tuple to be checked for a particular substring.
- “start”: An optional parameter indicating the starting position of the substring that needs to be checked.
- “end”: Another optional parameter indicating the ending position where the prefix is to be checked within the given string.
It’s important to note that the “start” and “end” parameters must have values within the range of [0-length-1] of the string. If these parameters are not provided, the startswith() method sets the start to 0 and the end value to the length of the string minus 1.
Return Value of startswith()
The startswith() method returns a boolean value, either True or False. It returns True only when the given string contains the provided prefix.
Examples of Using the startswith() Function in Python
Example 1: Checking if a URL starts with “http” or “https”
url = "https://www.example.com"if url.startswith(("http", "https")): print("The URL starts with 'http' or 'https'")
Output:
The URL starts with 'http' or 'https'
In this example, we use the startswith() function to check if a given URL starts with either “http” or “https”. We pass a tuple of prefixes as an argument to startswith() to check for multiple prefixes. Since the URL starts with “https”, which is one of the prefixes we specified, the program prints “The URL starts with ‘http’ or ‘https'”.
Example 2: Finding filenames that start with a particular prefix
filenames = ["example.txt", "test.txt", "image.jpg", "data.csv"]for filename in filenames: if filename.startswith("test"): print(f"{filename} starts with 'test'")
Output:
test.txt starts with 'test'
In this example, we use the startswith() function to find filenames in a list that start with the prefix “test”. We loop through each filename in the list and use startswith() to check if it starts with “test”. Since the filename “test.txt” starts with “test”, the program prints “test.txt starts with ‘test'”.
Example 3: Checking if a string starts with a substring in a given range
string = "Hello World"if string.startswith("l", 3, 6): print("The string starts with 'l' between positions 3 and 6")
Output:
The string starts with 'l' between positions 3 and 6
In this example, we use the startswith() function to check if a substring of the string “Hello World” that starts at position 3 and ends at position 6 (exclusive) starts with the character “l”. Since the substring “lo ” (note the space character at the end) does indeed start with “l”, the program prints “The string starts with ‘l’ between positions 3 and 6”.
Example 4: Checking if a string starts with a digit
string = "12345abc"if string.startswith(tuple("0123456789")): print("The string starts with a digit")else: print("The string does not start with a digit")
Output:
The string starts with a digit
In this example, we use the startswith() function to check if a given string starts with any digit. We pass a tuple of all digits as an argument to startswith(). Since the string “12345abc” starts with a digit “1”, the program prints “The string starts with a digit”.
Example 5: Checking if a string starts with any element of a list
string = "The quick brown fox jumps over the lazy dog"prefixes = ["brown", "red", "orange", "yellow", "green", "blue", "purple"]if string.startswith(tuple(prefixes)): print("The string starts with one of the colors in the list")else: print("The string does not start with any of the colors in the list")
Output:
The string starts with one of the colors in the list
In this example, we use the startswith() function to check if a given string starts with any element of a list of colors. We pass a tuple of colors as an argument to startswith(). Since the string “The quick brown fox jumps over the lazy dog” starts with the colour “brown”, which is one of the elements in the list, the program prints “The string starts with one of the colours in the list”.
These examples demonstrate some of the versatility of the startswith() function and show how it can be used in various contexts to check for prefixes in strings.
Endnotes
The startswith () function is a useful tool for checking if a string starts with a particular prefix. It can be used in a variety of applications. I hope this article helped you understand how and why the starts-with () method is used in Python.
Check Our More Python Blogs
FAQs
What is the difference between startswith() and find() in Python?
Both startswith() and find() functions can be used to search for a substring within a string, but they differ in the way they return their output. startswith() returns a boolean value (True or False) indicating whether the string starts with the specified substring or not, while find() returns the index of the first occurrence of the substring in the string (or -1 if the substring is not found).
Can startswith() be used to check for suffixes instead of prefixes?
No, the startswith() function is specifically designed to check whether a string starts with a specified prefix. To check for suffixes, you can use the endswith() function instead.
How can I check if a string starts with any of a list of prefixes in Python?
You can pass a tuple of prefixes as the argument to startswith() to check if the string starts with any of the prefixes. Alternatively, you can use a loop to iterate over the list of prefixes and call startswith() on each one until you find a match.
Can startswith() be used with non-string types in Python?
No, the startswith() function is specifically designed to work with strings in Python. If you want to check for prefixes in other types of objects, you will need to use a different approach.
What happens if I pass an empty string as the argument to startswith() in Python?
If you pass an empty string as the argument to startswith(), the function will always return True, because any string can be considered to start with an empty string.
This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio