Understanding Python startswith() Function

Understanding Python startswith() Function

5 mins read111 Views Comment
Updated on Aug 16, 2024 14:45 IST

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.

2023_03_Understanding-Break-Statement-in-C-26.jpg

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:

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

Recommended online courses

Best-suited Python courses for you

Learn Python with these high-rated online courses

– / –
3 months
Free
3 hours
Free
19 hours
– / –
4 months
Free
2 hours
Free
9 hours
₹3 K
3 weeks
– / –
– / –
– / –
40 hours

Syntax of Python startswith()

The syntax of startswith() function in Python is given as:

string.startswith(prefix, start, end)
Copy code

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'")
Copy code

Output:

The URL starts with 'http' or 'https'
Copy code

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'")
Copy code

Output:

test.txt starts with 'test'
Copy code

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")
Copy code

Output:

The string starts with 'l' between positions 3 and 6
Copy code

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")
Copy code

Output:

The string starts with a digit
Copy code

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")
Copy code

Output:

The string starts with one of the colors in the list
Copy code

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

How to Check if a Python String is a Palindrome
How to Check if a Python String is a Palindrome
A palindrome is a sequence of the word, phrases, or numbers that read the same backward as forward. In this article, we will discuss different methods how to check if...read more

How to Generate Random Numbers in Python?
How to Generate Random Numbers in Python?
In Data Science or Statistics, there are various instances where a programmer might need to work with random inputs. Python offers many predefined functions to generate and use random data....read more

For Loop in Python (Practice Problem) – Python Tutorial
For Loop in Python (Practice Problem) – Python Tutorial
For loops in Python are designed to repeatedly execute the code block while iterating over a sequence or an iterable object such as a list, tuple, dictionary, or set. This...read more

Calculator Program in Python: A Step-By-Step Guide
Calculator Program in Python: A Step-By-Step Guide
Looking for a powerful and user-friendly calculator program in Python? In this blog, we will discuss three different methods for calculator programs in Python. A calculator performs arithmetic operations along...read more

Conditional Statements in Python – Python Tutorial
Conditional Statements in Python – Python Tutorial
A conditional statement as the name suggests itself, is used to handle conditions in your program. These statements guide the program while making decisions based on the conditions encountered by...read more

How to Find an Armstrong Number Using Python
How to Find an Armstrong Number Using Python
Learn how to find Armstrong numbers using Python with our step-by-step guide. Discover the algorithm to identify these special numbers, which are equal to the sum of their own digits...read more

Difference Between Module and Package in Python
Difference Between Module and Package in Python
Confused with modules and packages in python, then this article is for you. This article briefly discusses the Difference Between Module and Package in Python. If you have a basic...read more

Constructors in Python: Definition, Types, and Rules
Constructors in Python: Definition, Types, and Rules
Constructor in python is a special method that is called when an object is created. The purpose of a python constructor is to assign values to the data members within...read more

Difference Between Methods and Functions in Python
Difference Between Methods and Functions in Python
In Python, methods and functions have similar purposes but differ in important ways. Functions are independent blocks of code that can be called from anywhere, while methods are tied to...read more

Star Pattern in Python
Star Pattern in Python
Pattern programs in Python are a type of problem that uses nested loops to produce different patterns of numbers, stars (*), or other characters. In this blog, we will dive...read more

Methods to Check for Prime Numbers in Python
Methods to Check for Prime Numbers in Python
Prime numbers are the building blocks of mathematics, and they have fascinated mathematicians for centuries. Regarding Python programming, there are different methods to check whether the given number is a...read more

Top 7 Online Python Compiler Picks for 2024
Top 7 Online Python Compiler Picks for 2024
Are you tired of installing Python on your computer? Don’t worry; we’ve got you covered with the top 7 online Python compilers for 2024! These compilers are like having a...read more

How to Compute Euclidean Distance in Python
How to Compute Euclidean Distance in Python
Euclidean Distance is one of the most used distance metrics in Machine Learning. In this article, we will discuss Euclidean Distance, how to derive formula, implementation in python and finally...read more

Bubble Sort Algorithm in Python
Bubble Sort Algorithm in Python
The Bubble Sort algorithm is a simple sorting method that iterates through a given list, compares every pair of neighboring items, and exchanges them if they are out of order....read more

How to Find the Factorial of a Number Using Python
How to Find the Factorial of a Number Using Python
In this article, we will discuss different methods to find the factorial of a number in python using for, while, ternary operator and math module. While practicing Python programming as...read more

Find the Second Occurrence of a Substring in Python String
Find the Second Occurrence of a Substring in Python String
During Python programming, you will come across instances where you would need to find the second occurrence of a substring in Python a given string. For example, finding the second...read more

Types of Functions in Python
Types of Functions in Python
A function is a block of code in Python that performs a particular task. It may take zero or more inputs and may or may not return one or more...read more

Difference Between Mutable and Immutable in Python
Difference Between Mutable and Immutable in Python
Data types in Python are categorized into mutable and immutable data types. Mutable data type is those whose values can be changed, whereas immutable data type is one in which...read more

ord() and chr() Function in Python
ord() and chr() Function in Python
ord () and chr() functions of Python are built-in functions that are used to convert a character to an integer and vice-versa. In this article, we will learn how to...read more

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.

About the Author
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