CodeBlanks Logo Icon CodeBlanks

startswith, endswith

Learn prefix/suffix checks with startswith and endswith.

startswith and endswith

startswith checks whether a string begins with a substring. endswith checks whether it ends:

"hello.py".endswith(".py")   # True
"http://...".startswith("http")  # True

Both return bool. These methods are very common for file extension checks, URL protocol checks and similar tasks.

Multiple substrings can be given as a tuple; if any matches, True is returned.

Multiple checks

Multiple substrings can be given as a tuple:

name = "photo.jpg"
name.endswith((".jpg", ".png", ".gif"))  # True

This is very useful when checking multiple options like file extensions. Using a tuple is shorter than writing multiple or() conditions.

Similarly, startswith also accepts a tuple.

Practice Check with endswith

Assign "photo.jpg" to filename. Assign filename.endswith(".jpg") to is_image. Then print print(is_image).

Starter code

main.py
# Check with endswith

Sample solution

main.py
filename = "photo.jpg"
is_image = filename.endswith(".jpg")
print(is_image)

Expected output

True

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the endswith call

Question
is_py = "hello.py".____(".py")
Answer
is_py = "hello.py".endswith(".py")

Explanation: endswith(".py") checks the ending.

2 What does "hello.py".endswith(".py") return?

  • False
  • True Correct answer
  • ".py"
  • Raises an error

Explanation: The string ends with ".py"; True is returned.

3 Match startswith and endswith

Term Meaning
startswith Start check
endswith End check
tuple Multiple options
bool Return type

All lessons in Beginner