Python String startswith() method is a built-in function that determines whether the given string starts with a specific sequence of characters. Let’s take a look at syntax and examples of the Python string startswith()
method.
Note: If you want to determine whether the given string ends with a specific sequence of characters, then you can use Python String endswith()
Syntax
The syntax of startswith()
method is:
str.startswith(prefix[, start[, end]])
Parameter
The startswith()
function can take three parameters
- prefix– string that needs to be checked in the main string
- start (optional) – Starting position where prefix needs to be checked within the string.
- end (optional) – Ending position where prefix needs to be checked within the string.
Return Value
The startswith()
function returns true if the string starts with the specified prefix. Otherwise, it returns false.
Note: The startswith()
function is case-sensitive
Example 1: startswith() method without start and end Parameters
text = "Welcome to Python Tutorials"
# startswith is case-sensitive, returns false
print(text.startswith('welcome'))
# returns true
print(text.startswith('Welcome'))
# returns true
print(text.startswith('Welcome to'))
Output
False
True
True
Example 2: startswith() method with start and end Parameters
text = "Welcome to Python Tutorials"
# returns true
result = text.startswith("Welcome", 0)
print(result)
# returns false
result = text.startswith("to", 1, 15)
print(result)
# returns true
result = text.startswith("to", 8, 10)
print(result)
Output
True
False
True
Passing Tuple to startswith()
It’s possible to pass a tuple as a prefix to the startswith()
method in Python. If the string starts with any item of the tuple, startswith()
function returns True. Otherwise, it returns False
text = "Welcome to Python Tutorials"
# returns true
result = text.startswith(('Welcome', 'Python', 'Tutorials'))
print(result)
# returns true
result = text.startswith(('to', 'Python', 'Tutorials'), 8)
print(result)
# returns true
result = text.startswith(('to', 'Python', 'Tutorials'), 11, 20)
print(result)
Output
True
True
True