Python's startswith() Method

Diving into Python's String class, we come across a nifty method called startswith(). This handy little tool checks if your string starts off with a particular prefix. Here's how you use it:

string.startswith(prefix, start index)

"String" is the variable you're working with.

The method requires one compulsory argument, the "prefix", which is the beginning bit you're hunting for in your string

If your string does indeed kick-off with the specified prefix, it will nod back with a True. If it's a no-show, you'll get a False.

The start index is an optional parameter. It allows you to kickstart your search from a start index other than zero - for instance, from the third character of the string instead of the first.

Here's a quick demo.

Let's start by creating this string.

>>> string = "Hello world!"

Next, we check if the string starts with "Hello".

>>> string.startswith("Hello")

Python then checks if "Hello" is indeed how your string begins.

In this case, the answer is a resounding yes. So, Python returns a True.

True

The startswith() method isn't just about starting at the beginning. You can also start your search from somewhere in the middle.

For instance, let's say you type string.startswith("Hello",2)

>>> string.startswith("Hello",2)

In this scenario, you've handed '2' as the second parameter to the startswith() function, signalling Python to start looking for the prefix "Hello" from the string's third character.

Here, it doesn't match. So, Python hands you a False.

False

Quick reminder: in string land, the first character is always labelled with an index of zero. That means the second character is tagged with a one, and the third with a two. So when you set the parameter as "2", you're directing the searchlight to start from the third character.
string example

Wrapping up, the startswith() method is your go-to tool when you need to check if a string begins with a certain prefix.

It can also be used in conjunction with other string methods to manipulate or analyze strings in Python."




Report a mistake or post a question




FacebookTwitterLinkedinLinkedin