Module 7 · Strings — topic 17 of 22
startswith()
startswith(prefix) checks whether a string begins with given text. Learn tuple arguments for several prefixes, start positions, case handling and practical uses in parsing and validation.
Learning objectives
- Test prefixes with startswith()
- Check several prefixes with a tuple
- Use startswith() for parsing commands and data
Definition
startswith(prefix) checks whether a string begins with given text. Learn tuple arguments for several prefixes, start positions, case handling and practical uses in parsing and validation.
Introduction
startswith(prefix) returns True if the string begins with prefix and False otherwise. It is clearer and safer than slicing and comparing: url.startswith("https://").
Why it matters
Many formats are identified by how they begin: URLs by their scheme, commands by a keyword, phone numbers by a country code, comment lines by #. startswith() makes these checks readable and never raises an index error.
Detailed explanation
startswith() reads more clearly than the slicing alternative text[:3] == "abc", and it doesn’t require you to count the prefix length correctly. When a prefix changes from "v1/" to "api/v1/", only the literal changes, not a slice position that someone might forget to update.
Prefixes carry meaning in many real-world formats. International phone numbers begin with + and a country code, Indian vehicle numbers with a state code such as KA or MH, Git branches often with feature/ or fix/, and environment variables in a project frequently share a prefix such as APP_. startswith() turns each of these conventions into a one-line check.
Because it returns a Boolean, startswith() fits naturally into conditions, comprehensions and the any() and all() functions: any(line.startswith("ERROR") for line in log_lines) tells you whether a log contains any errors.
startswith(prefix) compares the beginning of the string with prefix exactly; it is case-sensitive.
Pass a tuple to accept several prefixes: url.startswith(("http://", "https://")). A list is not accepted.
startswith(prefix, start) checks from a given position instead of the beginning.
An empty prefix always matches.
Unlike text[:len(prefix)] == prefix, startswith works even when the string is shorter than the prefix.
To remove a known prefix after checking, use removeprefix(prefix).
Syntax
- Returns True or False.
- A tuple checks several prefixes.
- Matching is case-sensitive.
Code examples
Checking beginnings
True False True
Case and position
True False True True
More examples
A tiny command parser
Not in list: bread Items: ['milk'] Final: ['milk', 'eggs']
Step-by-step explanation
- Lines starting with # are skipped as comments.
- lower() lets ADD and add both match the add command.
- cmd[4:] takes the text after "add " from the original line, keeping its capitalisation.
- A tuple of prefixes accepts both del and remove.
Expected output
Running “A tiny command parser” prints exactly:
Practical applications
- Web frameworks route requests by checking whether a path starts with /api/.
- Chat bots detect commands that start with /.
- Config readers skip lines that start with # or ;.
Best practices
- Prefer startswith over slicing comparisons.
- Use a tuple for several allowed prefixes.
- Normalise case for user input.
Common mistakes
Passing a list of prefixes
Avoid
Prefer
startswith accepts a string or a tuple, not a list.
Ignoring case
Avoid
Prefer
Normalise case first when input may vary.
Key takeaways
- startswith(prefix) tests the beginning of a string.
- A tuple of prefixes checks several at once.
- It is case-sensitive and never raises IndexError.
Try it yourself
- 1Check whether a mobile number starts with +91 or 0.
- 2From a list of file names, print only those that start with "report_".
Finished reading? Mark it complete to update your dashboard.
Suggested practice
17 questions cover the “Strings” module. Answers and explanations are revealed after you submit.
- BeginnerWhat is printed?
- BeginnerWhat is printed?
- BeginnerWhat is printed?