开始使用免费开始使用

在字符串中查找字符串

处理字符串时,我们经常关注字符串里包含哪些字符。例如,我们可能想知道,在一个曲奇列表中有多少项包含 Chocolate 这个词,或者有多少是以字母 C 开头。可以在字符串上使用 in 关键字和 .startswith() 方法来完成这些检查。我们也可以在列表推导中加入条件,形式为 [action for item in list if something is true]。以曲奇为例,可以写成 [cookie_name for cookie_name in cookies if 'chocolate' in cookie_name.lower()]。注意,这些检查区分大小写,因此我们在字符串上使用 .lower() 方法。我们还可以通过依次调用方法来"链式"使用它们。

本练习是课程的一部分

Python 的数据类型

查看课程

练习说明

  • 存储并打印一个以 s 开头的 girl_names 列表。
  • 存储并打印一个包含 angelgirl_names 列表。

交互式实操练习

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

# Store a list of girl_names that start with s: names_with_s
names_with_s = [____ for name in girl_names if ____.lower().____('____')]

print(names_with_s)

# Store a list of girl_names that contain angel: names_with_angel
names_with_angel = [name for name in ____ if '____' in name.____()]

print(names_with_angel)
编辑并运行代码