Python String startswith()

The Python startswith() string method is used to check if a specified string starts with a given prefix/substring or not. It is an inbuilt string function in Python.

  • The startswith() method returns true if the the string starts with the prefix that we are looking for and if it doesn't have that prefix then, in that case, this function returns false.

  • The parameter prefix of this function is case sensitive, which means study and Study are two different prefix values.

Python String startswith(): Syntax

Below we have a basic syntax of the startswith() method in Python:

str.startswith(prefix, beg=0,end=len(string))

Python String startswith(): Parameters

The description of the Parameters of startswith() is given below:

  • prefix

    This parameter is used to specify the substring which is the prefix.

  • start

    It is an optional parameter that is used to set a starting index for the matching boundary.

  • end

    It is also an optional parameter that is used to set the ending index of the matching boundary.

Python String startswith(): Returned Values

For the returned value there are two cases:

  • It returns true in the case if the string starts with a specified prefix or substring

  • It returns false in the case if the string does not start with a specified prefix.

Python String startswith(): Basic Example

Below we have an example to show the working of the startswith() function in python:

strA = 'Welcome to StudyTonight'
print(strA.startswith('Study'))

The output of the above code snippet will be:


True

Python String startswith(): Another Example

Let us see another code snippet where we see the case-sensitiveness of this method:

strA = 'Welcome to StudyTonight'
print(strA.startswith('study', 10))

The output of the above code snippet will be:


false

Note: As startswith() is a case sensitive function, study and Study are treated as different strings, and hence we got false as output of the above code.

Time for a Live Example!

Let us see a Live Example where we will use startswith() function in different situations and will see the output for the same:

Summary

In this tutorial, we have discussed the startswith() method of strings in Python which is used to check if the specified string starts with a given prefix or not.