Kodeclik Blog

Python startswith(): A Simple Guide

Let us assume you have a string such as “Kodeclik Online Academy”. The startswith() method can be used with such a string to check if it begins with a certain prefix. For instance, the program:
Note that “K” and “Kodeclik” are prefixes but “Kodeclik.com” is not.
Similarly, “Online” is not a prefix of “Kodeclik Online Academy” so that:

startswith() with Start Parameter

You can modify the behavior of Startswith() by specifying a position to consider as the start of the string rather than the default beginning of the string. For instance:
On the other hand,
both return:

startswith() with Start and End Parameters

Similarly, you can also pass an optional end parameter in addition to the start parameter (to indicate the substring within which the prefix needs to be found).
For instance:
all return:
Note that the end parameter must be at least he start position + search string’s length. Here the start position is 9 and the search string (i.e., “Online”) has length 6. So the end parameter must be at least 15. If we use a value less than this, such as:
We will obtain:
because the search prefix is not found within the prescribed boundaries. This will be tantamount to searching for a prefix longer than the string’s length. For instance:

startswith() with Multiple Prefixes

If you would like to search for multiple prefixes, you can pass a tuple of prefixes instead of a string as input. For instance:
The first print() statement returns True because the string begins with “Kodeclik”, one of the three acceptable prefixes. The second print() statement returns False because the string does not begin with any of the acceptable prefixes.
Note that in the case of the first print statement, while it returns True, the output does not give us any indication of which prefix was found in the given input, only that one of the three acceptable prefixes were found.
To make the second print() statement to be True, we can add start and end parameters like before:
This will output:
In this blogpost, you have learnt about the very useful Python startswith() method and how you can use it to detect the presence of specific prefixes. For instance, you can go through all sentences in a book and detect those that begin with a specific prefix of interest. Or, you can go through a list of all universities in the US and search for those that begin with a “University of” prefix. Also learn how to capitalize the first letters of words in a string in Python. Have fun!
Interested in more things Python? See our blogpost on Python's enumerate() capability. Also if you like Python+math content, see our blogpost on Magic Squares. Finally, master the Python print function!
Want to learn Python with us? Sign up for 1:1 or small group classes.

Join our mailing list

Subscribe to get updates about our classes, camps, coupons, and more.

Copyright @ Kodeclik 2024. All rights reserved.