How to Use startswith in Python: Syntax and Examples
In Python, use the
startswith() method on a string to check if it begins with a specified prefix. It returns True if the string starts with that prefix, otherwise False. You can also check multiple prefixes by passing a tuple of strings.Syntax
The startswith() method checks if a string starts with the given prefix.
string.startswith(prefix): ReturnsTrueifstringstarts withprefix.prefixcan be a string or a tuple of strings.- Optional
startandendparameters specify the substring range to check.
python
string.startswith(prefix, start=0, end=len(string))
Example
This example shows how to use startswith() to check if a string begins with a certain prefix or any of multiple prefixes.
python
text = "Hello, world!" # Check if text starts with 'Hello' print(text.startswith("Hello")) # True # Check if text starts with 'Hi' print(text.startswith("Hi")) # False # Check if text starts with either 'Hi' or 'Hello' print(text.startswith(("Hi", "Hello"))) # True # Check starting from index 7 print(text.startswith("world", 7)) # True
Output
True
False
True
True
Common Pitfalls
Common mistakes when using startswith() include:
- Passing a list instead of a tuple for multiple prefixes (only tuples work).
- Forgetting that
startswith()is case-sensitive. - Not using the optional
startandendparameters correctly.
Example of wrong and right usage:
python
# Wrong: using list instead of tuple text = "Python" print(text.startswith(["Py", "Ja"])) # Raises TypeError # Right: use tuple print(text.startswith(("Py", "Ja"))) # True # Case sensitivity print(text.startswith("py")) # False because 'p' != 'P'
Output
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
TypeError: startswith first arg must be str or a tuple of str, not list
True
False
Quick Reference
| Usage | Description |
|---|---|
| string.startswith(prefix) | Returns True if string starts with prefix. |
| string.startswith((p1, p2)) | Returns True if string starts with any prefix in tuple. |
| string.startswith(prefix, start) | Checks from index start to end of string. |
| string.startswith(prefix, start, end) | Checks substring from start to end indexes. |
Key Takeaways
Use
startswith() to check if a string begins with a specific prefix.Pass a tuple to check multiple prefixes at once, not a list.
startswith() is case-sensitive; 'Hello' and 'hello' differ.Optional
start and end let you check parts of the string.It returns a boolean:
True if the prefix matches, otherwise False.