python - 如何在python中的数组元素中找到特定的字符串

标签 python regex string list

我在 python 中有一个字符串列表,如果列表中的一个元素包含单词“parthipan”,我应该打印一条消息。但是下面的脚本不起作用

import re
a = ["paul Parthipan","paul","sdds","sdsdd"]
last_name = "Parthipan"
my_regex = r"(?mis){0}".format(re.escape(last_name))
if my_regex in a:
    print "matched"

列表的第一个元素包含单词“parthipan”,因此它应该打印消息。

最佳答案

如果你想用正则表达式做这个,你不能使用 in 运算符。请改用 re.search()。但它适用于字符串,而不是整个列表。

for elt in a:
    if re.search(my_regexp, elt):
        print "Matched"
        break # stop looking

或者更实用的风格:

if any(re.search(my_regexp, elt) for elt in a)):
    print "Matched"

关于python - 如何在python中的数组元素中找到特定的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36983172/

相关文章:

python - 导入错误 : No module named 'dask.dataframe' ;

Python Tkinter 笔记本小部件

JavaScript 正则表达式也可以匹配数字

mysql - 将字符串数据值转换为日期

php - 将 PHP 中的 openssl AES 转换为 Python AES

python - Pygame 地面碰撞检测和位置重置

c# - 去除非 ascii 字符但允许货币符号

php - 将格式化文本文件解析为 PHP 数组

java - 删除文本中数字中的多余空格

java - 如何打印我的 Java 对象而不得到 "SomeType@2f92e0f4"?