Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialBen Bassler
1,806 PointsChecking if a list has strings that begin with a certain letter.
"I'd like you to now only print continents that begin with the letter "A"." That is the task, but how do I check this?
continents = [
'Asia',
'South America',
'North America',
'Africa',
'Europe',
'Antarctica',
'Australia',
]
# Your code here
for i in continents:
print("* " + i)
3 Answers
Steven Parker
231,275 PointsYou can access individual characters in a string by indexing, using brackets similar to working with a list. For example, since index numbers start at 0, the first character of "mystring" would be "mystring[0]
".
You could then compare that to the letter "A" in a conditional expression as part of an "if" statement.
Ben Bassler
1,806 PointsAlright, I got it now! Thank you for your help.
Oleksandr Krasnovskyy
3,312 PointsWhats the final code? Doesnt work for me
for continent in continents: if i[0] == "A": print("* " + continent)
Steven Parker
231,275 PointsHis loop variable was "i", but yours is "continent". So you'll need to substitute the name in the "if" line to adapt it to your code.
Ben Bassler
1,806 PointsBen Bassler
1,806 PointsHow would the code look like? I don't think I quite understand it yet...
Steven Parker
231,275 PointsSteven Parker
231,275 PointsIn this case, in between the "for" and the "print", you might have something like this:
if i[0] == "A":