Python String startswith() Method
The startswith()
method is used to check if a string starts with a specified prefix. It returns True
if the string starts with the specified prefix, otherwise, it returns False
.
Syntax
string.startswith(prefix, start, end)
Parameter
prefix
: The string (or a tuple of strings) to check for at the beginning of the string.
start
(Optional): The starting index where the check begins (default is 0
).
end
(Optional): The ending index where the check ends (default is the end of the string).
Return Value
Returns True
if the string starts with the specified prefix, otherwise False
.
Examples
Basic Usage
text = "Python is awesome"
print(text.startswith("Python")) # Output: True
print(text.startswith("Java")) # Output: False
With start
Parameter
You can provide the start
parameter to the startswith()
method if you want to check whether a string begins with a specified prefix at a specific index.
text = "Python is awesome. Java is incredible too"
print(text.startswith("Java", 19)) # Output: True
With start
and end
Parameters
You can provide the start
and end
parameters to the startswith()
method if you want to check whether a string begins with a specified prefix within a specific range of indices.
text = "Python is awesome"
print(text.startswith("is", 7, 10)) # Output: True
Using a Tuple of Prefixes
You can provide a tuple of strings to the startswith()
method if you want to check whether a string begins with any of the specified prefixes.
text = "Python is awesome"
print(text.startswith(("Java", "Python", "Ruby"))) # Output: True
Case-Sensitivity
The startswith()
method is case-sensitive, meaning it treats uppercase and lowercase letters as distinct characters.
text = "Python is awesome"
print(text.startswith("python")) # Output: False
In this example, the startswith()
method checks if the string starts with the exact lowercase prefix "python"
but the string text
starts with prefix "Python"
with an uppercase "P"
. Since the cases don’t match, the method returns False
.
If you need to check if a string ends with a specified suffix, you can use the endswith()
method.