Searching Strings

Searching Strings

in checks whether one string contains another:

print("cat" in "concatenate")
print("dog" in "concatenate")

Output:

True
False

startswith and endswith check the ends. Both return booleans:

filename = "report.pdf"
print(filename.endswith(".pdf"))
print(filename.startswith("draft"))

Output:

True
False

find returns the index where a substring first appears, or -1 when it is absent:

email = "ada@example.com"
print(email.find("@"))
print(email.find("!"))

Output:

3
-1

All of these are case-sensitive: "PDF" in "report.pdf" is False. To search regardless of case, lowercase both sides first.

Exercise

  1. Define a function named is_image with one parameter, filename.
  2. It returns True when filename ends with ".png" or ".jpg", regardless of case — "PHOTO.JPG" counts.

is_image("cat.png") returns True. is_image("cat.txt") returns False.

Run your code to see the output, then press Submit.

Tests

import unittest


class TestIsImage(unittest.TestCase):
    def test_png_is_an_image(self):
        self.assertIs(is_image("cat.png"), True)

    def test_jpg_is_an_image(self):
        self.assertIs(is_image("cat.jpg"), True)

    def test_uppercase_jpg_is_an_image(self):
        self.assertIs(is_image("PHOTO.JPG"), True)

    def test_txt_is_not_an_image(self):
        self.assertIs(is_image("cat.txt"), False)

    def test_png_in_the_middle_does_not_count(self):
        self.assertIs(is_image("png.txt"), False)
def is_image(filename):
    lowered = filename.lower()
    return lowered.endswith(".png") or lowered.endswith(".jpg")


print(is_image("cat.png"))
print(is_image("PHOTO.JPG"))
print(is_image("cat.txt"))
Solution hidden. Give it a real try first.

Sign in to join the discussion.

No comments yet. Be the first to ask a question.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.