Information about cookies on this page

Our website uses cookies to ensure the functionality of the website, to collect and analyze information about the performance and usage of the website. Privacy Policy

  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in
  
  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in

Beginnings and Ends

Often you need to know how a text starts or ends. Is the file a picture? Is the web address secure? Is the chat message a command? The methods startswith() and endswith() answer with True or False:

file_name = "holiday.jpg"
url = "https://startcoder.com"
message = "/help"
print(file_name.endswith(".jpg"))
print(url.startswith("https://"))
print(message.startswith("/"))
print(file_name.startswith("work"))

This prints:

True
True
True
False

Why not in? Because in finds a part anywhere. ".jpg" in "photo.jpg.exe" is True, but that file isn't a picture at all: its name ends with .exe, so it's a program. "photo.jpg.exe".endswith(".jpg") is False.

Both methods return a boolean, so you'll mostly use them in conditions. And they care about case too. Cameras often name their photos in capitals, such as IMG_2031.JPG, and "IMG_2031.JPG".endswith(".jpg") is False. So turn the name into lowercase first:

files = ["IMG_2031.JPG", "notes.txt", "cat.jpg"]
for name in files:
    if name.lower().endswith(".jpg"):
        print("Photo:", name)

This prints:

Photo: IMG_2031.JPG
Photo: cat.jpg

Notice that the program prints name, not name.lower(). The lowercase text is only for the check, and the name keeps its letters as they were.

Instructions

  1. 1

    Print the photos in the list downloads: the names that end with .jpg, in capitals or not. Print each name on its own line, as it's written in the list: holiday.jpg, IMG_2031.JPG and IMG_2032.jpg. Keep the line with downloads: the exercise also tries other lists in it.

  2. 2

    The camera's photos are the ones whose names start with IMG_. Below the loop, count them and print From the camera: 2.

Back

6/12

  1. 1. Upper and Lower Case
  2. 2. Trimming Spaces
  3. 3. Replacing Text
  4. 4. Quiz: Text Methods
  5. 5. Searching in Text
  6. 6. Beginnings and Ends
  7. 7. Splitting Text
  8. 8. Joining a List
  9. 9. Slices
  10. 10. Quiz: Slices
  11. 11. Decimal Places
  12. 12. Summary
Next

Try it yourself

Do this exercise right here in your browser. No account needed.