- 使用 find() 方法:
strings = ["hello world", "apple [pie]", "orange [juice]"]
result = []
for s in strings:
if s.find("[") != -1:
result.append(s)
#print("[在strings中")
else:
print("[不在strings中")
print(result)
输出:
['apple [pie]', 'orange [juice]']
这里,我们遍历了字符串列表 strings 中的每个字符串,使用 find() 方法查找字符串中是否包含 [,如果返回值不等于 -1,则说明字符串中包含 [,将该字符串添加到结果列表 result 中。
- 使用正则表达式:
import re
strings = ["hello world", "apple [pie]", "orange [juice]"]
result = []
for s in strings:
if re.search("\[", s):
result.append(s)
print(result)
输出:
['apple [pie]', 'orange [juice]']
这里,我们使用了 re.search() 方法来查找字符串中是否包含 [,如果匹配成功,则说明字符串中包含 [,将该字符串添加到结果列表 result 中。
- Python 的列表推导式来筛选出含有 [ 的字符串
strings = ["hello world", "apple [pie]", "orange [juice]"]
result = [s for s in strings if "[" in s]
print(result)
输出:
['apple [pie]', 'orange [juice]']
我们使用列表推导式遍历字符串列表 strings 中的每个字符串,并使用条件语句 if “[” in s 来判断字符串中是否包含 [。如果条件成立,则将该字符串添加到结果列表 result 中。
通过以上方法,可以过滤出含有 [ 的字符串。