Student Handbook

Student Handbook

Open in ChatGPT
Ask ChatGPT about this page
Open in Claude
Ask Claude about this page

str.startswith

Checks how a string begins (or, with endswith, how it ends).

Synopsis

text.startswith(prefix)
text.endswith(suffix)

Description

Both return True or False, so they fit straight into an if.

Parameters

Name Meaning
prefix / suffix The text to look for. It can also be a tuple of choices: ("y", "Y").

Return value

A bool.

Example

print("hello.py".endswith(".py"))
print("Hello".startswith("He"))
print("Hello".startswith("he"))

It prints:

True
True
False

Common mistake

answer = "Yes"
print(answer.startswith("y" or "Y"))

It prints:

False

"y" or "Y" is worked out first and is just "y". Write answer.lower().startswith("y") instead.

See also

in, str.lower

str.startswith in the Python documentation

Last updated 2 weeks ago