Python String startswith() Method

Determines whether the string starts with a given substring

Usage

The startswith() method returns True if the string starts with the specified prefix, otherwise returns False.

You can limit the search by specifying optional arguments start and end.

startswith() also accepts a tuple of prefixes to look for.

Syntax

string.startswith(prefix,start,end)

Python string startswith() method parameters
ParameterConditionDescription
prefixRequiredAny string you want to search
startOptionalAn index specifying where to start the search.
Default is 0.
endOptionalAn index specifying where to stop the search.
Default is the end of the string.

Basic Example

# Check if the string starts with 'Bob'
S = 'Bob is a CEO.'
x = S.startswith('Bob')
print(x)
# Prints True

Limit startswith() Search to Substring

To limit the search to the substring, specify the start and end parameters.

# Check if the substring (9th to 18th character) starts with 'CEO'
S = 'Bob is a CEO at ABC'
x = S.startswith('CEO',9,18)
print(x)
# Prints True

Provide Multiple Prefixes to Look for

You can provide multiple prefixes to the method in the form of a tuple. If the string starts with any item of the tuple, the method returns True, otherwise returns False.

S = 'Bob is a CEO'
prefixes = ('Bob','Max','Sam')
x = S.startswith(prefixes)
print(x)
# Prints True

S = 'Max is a COO'
prefixes = ('Bob','Max','Sam')
x = S.startswith(prefixes)
print(x)
# Prints True