Get startedGet started for free

Combining multiple strings

F strings work great for a few variables, but what if you want to combine a whole list of variables into a string. You can use the "".join() method for just that. You put what you want to join the list items with inside the "" and then pass the list into the join() method. For example, if you want to join all the items in a list named cookies with a comma and space it would look like ", ".join(cookies).

In this exercise, you'll use these skills to convert a list of the top ten boy names into a sentence stored in a string.

This exercise is part of the course

Data Types in Python

View Course

Exercise instructions

  • Make a string that contains: The top ten boy names are: and store it as preamble.
  • Make a string that contains: , and and store it as conjunction.
  • Make a string that combines the first 9 names in boy_names list with a comma and store it as first_nine_names.
  • Make an f-string that contains preamble, first_nine_names, conjunction, the final item in boy_names and a period.

Hands-on interactive exercise

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

# The top ten boy names are:  as preamble
____ = "The top ten boy names are: "

# , and as conjunction
conjunction = ____

# Combines the first 9 names in boy_names with a comma and space as first_nine_names
first_nine_names = "____".join(boy_names[____:____])

# Print f-string preamble, first_nine_names, conjunction, the final item in boy_names and a period
print(f"{____}{first_nine_names}{conjunction} {____[-1]}.")
Edit and Run Code