正在检查lis中的元素

2024-10-02 08:22:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我想做一个函数,里面有元素的列表(字符串) 接下来是第二个长字符串示例:

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

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

示例

List = ['href','a']

检查“href”是否在第二个字符串中 是的,是

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

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


Tags: 函数字符串https元素示例target列表list
1条回答
网友
1楼 · 发布于 2024-10-02 08:22:22

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

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或者。。。。。。如果在里面,我想把它作为str

所以你想在你的代码中使用regex来查找所有的.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

相关问题 更多 >

    热门问题