Skip to content

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.

Beginner 8 min read·Lesson 98 of 306 in Python Programming

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

Python
if text.startswith(prefix):
pass
if url.startswith(("http://", "https://")):
pass
  • Returns True or False.
  • A tuple checks several prefixes.
  • Matching is case-sensitive.

Code examples

Checking beginnings

Python
url = "https://skills.kenholt.info"
print(url.startswith("https://"))
print(url.startswith("http://"))
print(url.startswith(("http://", "https://")))
Output
True
False
True

Case and position

Python
line = "# comment"
print(line.startswith("#"))
print("Python".startswith("py"))
print("Python".lower().startswith("py"))
print("ab-cd".startswith("cd", 3))
Output
True
False
True
True

More examples

A tiny command parser

Python
commands = ["add milk", "del bread", "list", "# a note", "ADD eggs"]
items = []
for raw in commands:
cmd = raw.strip()
if cmd.startswith("#"):
continue
lowered = cmd.lower()
if lowered.startswith("add "):
items.append(cmd[4:])
elif lowered.startswith(("del ", "remove ")):
name = cmd.split(maxsplit=1)[1]
if name in items:
items.remove(name)
else:
print("Not in list:", name)
elif lowered == "list":
print("Items:", items)
print("Final:", items)
Output
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:

TextOutput
Not in list: bread
Items: ['milk']
Final: ['milk', 'eggs']

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

name.startswith(["Mr", "Ms"])

Prefer

name.startswith(("Mr", "Ms"))

startswith accepts a string or a tuple, not a list.

Ignoring case

Avoid

cmd.startswith("add") # misses “Add”

Prefer

cmd.lower().startswith("add")

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

  1. 1
    Check whether a mobile number starts with +91 or 0.
  2. 2
    From 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?
Practise this module