MulaiMulai sekarang secara gratis

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.

Latihan ini adalah bagian dari kursus

Data Types in Python

Lihat Kursus

Petunjuk latihan

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

Latihan interaktif praktis

Cobalah latihan ini dengan menyelesaikan kode contoh berikut.

# 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 dan Jalankan Kode