Python String startswith() Method Tutorial

Python string type provides different methods to work with strings. The startswith() method is provided by the string types which are used to check if the string starts with the specified string. Alternatively, the search can be restricted for the specified start and end indexes.

String startswith() Syntax

The startswith() method has the following syntax where the first argument is required and other arguments are optional. The startswith() method returns boolean values True or False according to the situation.

STRING.startswith(TERM,START_INDEX,END_INDEX)
  • STRING is the string where the TERM is searched inside it.
  • TERM is a string which may consist of single or more characters and searched inside STRING. By default matched from the start of the STRING.
  • START_INDEX is optional and if not specified the TERM searched from the start of STRING. START_INDEX is used to search for the specified index for the STRING.
  • END_INDEX is the end index number which should be higher than START_INDEX.

Check If String Starts With Specified String

In this example, we check if the string “python” is the start of the “python is a lovely programming language” string.

str = "python is a lovely programming language"

a=str.startswith('python')

b=str.startswith('py')

c=str.startswith('language')

print(a)
//True

print(b)
//True

print(c)
//False

Check If Specified Start Index Contains Specified String

By default, the TERM is searched from the index number 0 or the start of the STRING. The START_INDEX parameter is used to specify the start index for the search.

str = "python is a lovely programming language"

a=str.startswith('python',18,25)

b=str.startswith('py'0,4)

c=str.startswith('language',18,25)

print(a)
//False

print(b)
//True

print(c)
//True

Check If String Starts With One Of The Specified Strings (Provided As Tuple)

In some cases, we may need to search multiple terms inside a string and check if one of them matches. The tuple type can be used to specify multiple search terms to search inside the string.

str = "python is a lovely programming language"

a=str.startswith(('python','language','programming'))

b=str.startswith(('python','php','java'),10)

print(a)
//True

print(b)
//False

Leave a Comment