python 过滤出含有“[”的字符串

  1. 使用 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 中。

  1. 使用正则表达式:
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 中。

  1. 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 中。

通过以上方法,可以过滤出含有 [ 的字符串。

  • 11
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值