Get startedGet started for free

Finding strings in other strings

Many times when we are working with strings, we care about which characters are in the string. For example, we may want to know how many cookies in a list of cookies have the word Chocolate in them, or how many start with the letter C. We can perform these checks by using the in keyword and the .startswith() method on a string. We can also use conditionals on a list comprehension in the form of [action for item in list if something is true]. Using our cookies examples, it would be something like [cookie_name for cookie_name in cookies if 'chocolate' in cookie_name.lower()]. Note these checks are case sensitive so we're using the .lower() method on the string. We can also "chain" methods together by calling them one after the other.

This exercise is part of the course

Data Types in Python

View Course

Exercise instructions

  • Store and print a list of girl_names that start with s.
  • Store and print a list of girl_names with angel in them.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# Store a list of girl_names that start with s: names_with_s
names_with_s = [____ for name in girl_names if ____.lower().____('____')]

print(names_with_s)

# Store a list of girl_names that contain angel: names_with_angel
names_with_angel = [name for name in ____ if '____' in name.____()]

print(names_with_angel)
Edit and Run Code