Summary: in this tutorial, you’ll learn how to use the Python string startswith()
method to check if a string begins with another string.
Introduction to the Python string startswith() method
The startswith()
method returns True
if a string starts with another string. Otherwise, it returns False
.
The following shows the syntax of the startswith()
method:
str.startswith(prefix, [,start [,end ])
Code language: Python (python)
The startswith()
method accepts three parameters:
prefix
is a string or a tuple of strings to search for. Theprefix
parameter is mandatory.start
is the position that the method starts looking for theprefix
. Thestart
parameter is optional.end
is the position in the string that the method stops searching for theprefix
. Theend
parameter is also optional.
Note that the startswith()
method is case-sensitive. In other words, it will look for the prefix
case-sensitively.
Python string startswith() method examples
Let’s take some examples of using the string startswith()
method.
1) Using the startswith() method to check if a string begins with another string
The following example shows how to use the string startswith()
method to check if a string starts with another string:
s = 'Make it work, make it right, make it fast.'
result = s.startswith('Make')
print(result)
Code language: Python (python)
Output:
True
Code language: Python (python)
As mentioned earlier, the startswith()
method searches for a string case-sensitively. Therefore, the following example returns False
:
s = 'Make it work, make it right, make it fast.'
result = s.startswith('make')
print(result)
Code language: Python (python)
Output:
False
Code language: Python (python)
2) Using the startswith() method with a tuple
The following example uses the startswith()
method to check if a string starts with one of the strings in a tuple:
s = 'Make it work, make it right, make it fast.'
result = s.startswith(('Make','make'))
print(result)
Code language: PHP (php)
Output:
True
Code language: PHP (php)
3) Using the startswith() method with the start parameter
The following example illustrates how to use the startswith()
method to check if the string starts with the word make in lowercase starting from position 14:
s = 'Make it work, make it right, make it fast.'
result = s.startswith('make', 14)
print(result)
Code language: Python (python)
Output:
True
Code language: Python (python)
Summary
- Use the Python string
startswith()
method to determine if a string begins with another string.