开始使用免费开始使用

合并多个字符串

f-string 适合处理少量变量,但如果您想把整个变量列表合并成一个字符串,该怎么办?这时可以使用 "".join() 方法。把用于连接列表元素的分隔符放在 "" 中,然后将列表传入 join() 方法。例如,如果您要把名为 cookies 的列表中的所有元素用逗号和空格连接,可以写作 ", ".join(cookies)

在本练习中,您将用这些技巧把前 10 个男孩名字的列表转换为一个保存在字符串中的句子。

本练习是课程的一部分

Python 的数据类型

查看课程

练习说明

  • 创建一个包含 The top ten boy names are: 的字符串,保存为 preamble
  • 创建一个包含 , and 的字符串,保存为 conjunction
  • boy_names 列表中的前 9 个名字用逗号连接成一个字符串,保存为 first_nine_names
  • 创建一个 f-string,依次包含 preamblefirst_nine_namesconjunctionboy_names 的最后一个元素和句号。

交互式实操练习

通过完成这段示例代码来试试这个练习。

# 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]}.")
编辑并运行代码