今天接到一个需求,客户给了一堆特殊字符,说不能允许某些字段中存在某某字符,然后想到了下面两个方法, 进行对比
一、想的是直接把这些特殊字符循环去匹配 如下
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