字符串a = “not 404 found 张三 99 深圳”,每个词中间是空格,用正则过滤掉英文和数字,最终输出"张三 深圳"
a = "not 404 found 张三 99 深圳"
import re
s = a.split(' ')
k = re.findall('\d+|[a-zA-Z]+',a)
打印s和k:
[‘not’, ‘404’, ‘found’, ‘张三’, ‘99’, ‘深圳’]
[‘not’, ‘404’, ‘found’, ‘99’]
下一步,就是求列表s和k的差集
方法1:用集合set
print(' '.join(list(set(s).difference(set(k)))))
方法2:写列表解析式或循环判断,本例用列表解析式完成
l = [i for i in s if i not in k]
print(' '.join(l))
运行结果:
张三 深圳