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
Oefeninstructies
- Make a string that contains:
The top ten boy names are:and store it aspreamble. - Make a string that contains:
, andand store it asconjunction. - Make a string that combines the first 9 names in
boy_nameslist with a comma and store it asfirst_nine_names. - Make an f-string that contains
preamble,first_nine_names,conjunction, the final item inboy_namesand 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]}.")