Python String startswith() Function
The String startswith()
method checks if a string starts with a specified prefix. It returns True
if the string starts with the specified prefix, and False
otherwise.
Syntax
my_string.startswith(prefix, start, end)
startswith() Parameters
Python String startswith()
function parameters:
Parameter | Condition | Description |
---|---|---|
prefix | Required | Any string you want to search |
start | Optional | An index specifying where to start the search. Default value is 0 . |
end | Optional | An index specifying where to stop the search. Default value is the end of the string. |
startswith() Return Value
Python String startswith()
function returns a boolean:
True
if a string starts with the specified suffix.False
if a string does not start with the specified suffix.
Examples
Example 1: Check if a string starts with a given prefix
For example, let's check if the string starts with est
:
my_str = 'Big, Bigger, Biggest'
prefix = 'Big'
result = my_str.startswith(prefix)
print(result) # Output: True
output
True
If the prefix does not appear as prefix of the given string, then startswith()
method will return False
:
my_str = "Big, Bigger, Biggest"
prefix = 'Aaa'
result = my_str.startswith(prefix)
print(result) # Output: False
output
False
Example 2: Check if a string starts with a given prefix with start
and end
indexes
If you want to limit the search to a substring of the given string, you can specify the start
parameter and/or the end
parameter.
my_str = 'Big, Bigger, Biggest'
prefix = "Big"
# startswith()
result = my_str.startswith(prefix)
print(result) # Output: True
# startswith() after 4th index
result = my_str.startswith(prefix, 5)
print(result) # Output: True
# startswith() between 4th and 6th index
result = my_str.startswith(prefix, 4, 6)
print(result) # Output: False
output
True
True
False
Example 3: Check if a string starts with a Tuple of possible prefixes
You can pass multiple prefixes to the startswith()
method in the form of a Tuple. If the string starts with any item of the tuple, the method returns True
, otherwise returns False
.
my_str = 'Tom is a CEO'
prefixes = ('Tom','David','Anna')
result = my_str.startswith(prefixes)
print(result) # Output: True
output
True
my_str = 'Tom is a Dev'
prefixes = ('CFO','CEO','COO')
result = my_str.startswith(prefixes)
print(result) # Output: False
output
False
It works also with start
and end
parameters:
my_str = 'Tom is a CEO and a Dev'
prefixes = ('CFO','CEO','COO')
print(my_str[9:16]) # Output: a CEO
result = my_str.startswith(prefixes, 9, 16)
print(result) # Output: True
output
CEO and
True