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
FalseWhy 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.jpgNotice 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
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.JPGandIMG_2032.jpg. Keep the line withdownloads: the exercise also tries other lists in it. - 2
The camera's photos are the ones whose names start with
IMG_. Below the loop, count them and printFrom the camera: 2.