下面是一个示例代码,实现了循环遍历一个项目列表,并只输出包含特定字符串的项:
items = ['apple', 'banana', 'orange', 'kiwi', 'grape', 'mango']
search_string = 'an'
for item in items:
if search_string in item:
print(item)
在这个例子中,我们定义了一个项目列表 items
,包含了一些水果名称。然后,我们定义了一个字符串 search_string
,表示我们要搜索的子字符串。接下来,我们使用 for
循环遍历列表中的每一项。在循环内部,我们使用 in
运算符判断 search_string
是否在当前项中。如果是,就使用 print()
函数输出该项。
这样,运行上述代码,将会输出包含字符串 "an" 的项,即 "banana" 和 "mango"。