Aan de slagGa gratis aan de slag

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.

Deze oefening maakt deel uit van de cursus

Data Types in Python

Cursus bekijken

Oefeninstructies

  • 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.

Praktische interactieve oefening

Probeer deze oefening eens door deze voorbeeldcode in te vullen.

# 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]}.")
Code bewerken en uitvoeren