Python 判断某字符串 是否包含另一字符串的任意一个字符

    今天接到一个需求,客户给了一堆特殊字符,说不能允许某些字段中存在某某字符,然后想到了下面两个方法, 进行对比

一、想的是直接把这些特殊字符循环去匹配  如下

    text = 'uhfweiuohfhsaifdjfgyius[/;'
    spechars =  '><{}[]!@“,‘'
    is_exist = False
    for c in spechars:
        if c in text:
            is_exist = True
            pass
    print(is_exist)

  这里看下这段代码的分析结果

Total time: 4.1163e-05 s   # 总时长
Function: strfor at line 98
# Hits  调用次数    %Time: 耗时占用的百分比  Per Hit:每次调用占用的时间

Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
    98                                           def strfor():
    99         1            4      4.0      2.9      text = 'uhfweiuohfhsaifdjfgyius[/;'
   100         1            2      2.0      1.5      spechars =  '><{}[]!@“,‘'
   101         1            1      1.0      0.7      is_exist = False
   102        12           14      1.2     10.2      for c in spechars:
   103        11           13      1.2      9.5          if c in text:
   104         1            2      2.0      1.5              is_exist = True
   105         1            0      0.0      0.0              pass
   106         1          100    100.0     73.0      print(is_exist)
   107         1            1      1.0      0.7      return True

二 、直接取两个字符串的交集 这种方法不仅代码简单且执行效率要优于上述循环匹配 代码如下 

    text = 'uhfweiuohfhsaifdjfgyius[/;'
    spechars =  '><{}[]!@“,‘'
    is_exist = True if set(text).intersection(spechars) else False
    print(is_exist)

这里是这段代码的分析结果

Total time: 2.01308e-05 s   # 总时长
Function: StrMatch at line 80
Hits  调用次数    %Time: 耗时占用的百分比  Per Hit:每次调用占用的时间

Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
    80                                           def StrMatch():
    81                                               """
    82                                               
    83                                               :return: 
    84                                               """""
    85         1            5      5.0      7.5      text = 'uhfweiuohfhsaifdjfgyius[/;'
    86         1            2      2.0      3.0      spechars =  '><{}[]!@“,‘'
    87                                               # anser = set(text).intersection(spechars)
    88         1           14     14.0     20.9      is_exist = True if set(text).intersection(spechars) else False
    89         1           44     44.0     65.7      print(is_exist)
    90         1            2      2.0      3.0      return True

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值