Content · Programming · Python

Python str.startswith Method: Usage and Examples

str.startswith(prefix, start, end) tests whether the selected portion of a string begins with a prefix. It can accept a tuple of prefixes; matching is case-sensitive. Learn with a clear example and common mistakes to.

2 views Published Oct 17, 2026 Updated Oct 18, 2026 Admin

This guide explains str.startswith Method: Usage and Examples through a focused example and practical reasoning. No prior knowledge of this specific operation is required.

Understanding the Concept


str.startswith(prefix, start, end) tests whether the selected portion of a string begins with a prefix. It can accept a tuple of prefixes; matching is case-sensitive.

When You Would Use This


Check whether a message belongs to a known alert category.

Step-by-Step Example


messages = ["WARN: low disk", "ERROR: failed", "INFO: done"]
for message_text in messages:
    is_important = message_text.startswith(("WARN:", "ERROR:"))
    print(message_text, is_important)

How the Example Works


The warning and error lines are flagged, while the information line is not. The tuple lets one call test several alternatives without a manual chain of or comparisons.

Example Output


WARN: low disk True
ERROR: failed True
INFO: done False

Try It Yourself


Accept lines starting with either "DEBUG:" or "TRACE:".

Common Beginner Mistakes


  • Expecting case-insensitive prefix matching.
  • Assuming passing a list works instead of a tuple.
  • Confusing a prefix test with finding a substring anywhere in the text.

Key Takeaways


  • str.startswith(prefix, start, end) tests whether the selected portion of a string begins with a prefix.
  • The warning and error lines are flagged, while the information line is not.
  • Avoid this mistake: Expecting case-insensitive prefix matching.
Share this resourceSend this page to someone who may find it useful.