检查列表中的元素

Checking for elements in list

我想做一个函数,里面有元素列表(字符串) 然后我有第二个长字符串示例:

<a href="https://ertfwetwer" target="_blank">[Nerve Center]</a>

我想检查列表中的某个元素是否在该字符串中。 如果是,我想将该元素存储在某个变量中。

示例

List = ['href','a']

检查 "href" 是否在第二个字符串中 是的

将“href”存储在某个变量中。

我希望它像这样工作。但是我不知道该怎么做。

检查字符串中列表元素的主要方法是:

s= '''<a href="https://ertfwetwer" target="_blank">[Nerve Center]</a>'''
my_list=['href','a']

   def checker(mylist, my_string)
     new = list()

     for i in mylist:
        if i in my_string: # if elements is in string (you can check only special elements )
            print i ,'is in string'
            new.append(i) #storing result to new list 

   checker (my_list, s)

输出:

href is in string
a is in string

但是因为你说 我有来自页面源的长字符串,我想看看 .jpg 或 .png 或 .swf 或 .wbm 或......是否在里面我想把它存储在一些 var 中作为 str

所以您想在代码中使用正则表达式来查找长字符串中的所有 .jpg 或更多格式!假设您有

s= '''<a href="https://ertfwetwer" target="_blank">[Nerve Center]   
myname.jpg another.pdf mynext.xvf </a>'''

所以你想检查 .jpg 和另一个格式化的

my_list=['.jpg','.pdf']

for i in my_list:
 if i in s:
  print i ,'is in string'

您还可以找到他们的名字:

import re
s= '''<a next.pdf href="https://ertfwetwer" target="_blank">[Nerve Center] myfile.jpg another.pdf </a>'''

 re.findall(r'([^\s]+).jpg|([^\s]+).pdf',s)

输出:

[('myfile', ''), ('', 'another')]

甚至

for i in  re.findall(r'([^\s]+).jpg|([^\s]+).pdf',s):
    for j in i:
        print j.strip(' ')



next
myfile
another