Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท String Methods

Python str.startswith() method

Reference for Python str.startswith(): test whether a string begins with a prefix or any prefix from a tuple, with start and end bounds and common mistakes.

The str.startswith() method returns True if a string begins with the given prefix and False otherwise. The prefix can also be a tuple of prefixes, in which case the result is True when the string begins with any one of them.

Use it for protocol checks, command names, file name patterns and similar tests. It reads better and is less error-prone than comparing a slice such as s[:5] == "http:".

Python
print("https://example.com".startswith("https"))   # True

Try it

Python Checking prefixes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python Bounds and the list mistake

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Syntax

Python
str.startswith(prefix)
str.startswith(prefix, start)
str.startswith(prefix, start, end)
Name Description
prefix A string, or a tuple of strings, to look for at the beginning.
start Optional. Index at which to start comparing (default 0).
end Optional. Index at which to stop comparing, exclusive (default len(s)).

Return value: True or False.

Raises: TypeError if prefix is not a string or a tuple of strings (lists and sets are rejected).

Usage notes

  • Case-sensitive. Lower-case the string first for a caseless test.
  • Tuple, not list. Pass several prefixes as a tuple; convert a list with tuple(items).
  • Empty prefix is always matched, so s.startswith("") is True; an empty tuple gives False.
  • Bounds work like a slice: s.startswith(p, start, end) tests s[start:end], so a prefix longer than the slice cannot match.
  • Remove the prefix with removeprefix() (Python 3.9+), which needs no test first.
  • Do not confuse with lstrip(), which strips characters from a set.
  • Paths: use pathlib methods such as Path.is_relative_to() instead of string prefixes, because "/usr/lib2".startswith("/usr/lib") is true.
  • Also on bytes and bytearray, with bytes arguments.