Python Introducing Lists Using Lists Continental

Joshua van Tongeren
Joshua van Tongeren
3,350 Points

How do I only print items that start with "A"?

I've looked at the videos again and can't find any reference to accessing characters in the string by index.. need help!

continents.py
continents = [
    'Asia',
    'South America',
    'North America',
    'Africa',
    'Europe',
    'Antarctica',
    'Australia',
]
for continent in continents:
    print("* " + continent)

2 Answers

Steven Parker
Steven Parker
171,342 Points

You can use indexing on a string to isolate a particular character. And index numbers start with 0, so the first character of "mystring" would be "mystring[0]".

Then you just need to compare that to "A".

I'll bet you can get it now, but write again if you need more help.

First Solution:

continents = [
    'Asia',
    'South America',
    'North America',
    'Africa',
    'Europe',
    'Antarctica',
    'Australia',
]
for continent in continents:
    if continent[0] == 'A':
        print("* " + continent)

Second Solution

There is method in python called startswith() #Checks if String Starts with the Specified String return True if match else return False.

continents = [
    'Asia',
    'South America',
    'North America',
    'Africa',
    'Europe',
    'Antarctica',
    'Australia',
]

for continent in continents:
    if continent.startswith("A"):
        print("* " + continent)