Python 如何在字符串匹配中使用通配符

Python 如何在字符串匹配中使用通配符,python,string,Python,String,我如何做到这一点: if 'class="*word*"' in html: print "True." else: print "False." 要像在Linux中一样使用*作为通配符字符?您需要查看模块。这将允许您执行正则表达式,并完成与linux命令行中*相同的操作。您可以使用模块中的正则表达式进行通用模式匹配 但是,如果您使用HTML并尝试匹配标记,我建议您查看并使用其parse函数和cssselect,以获得所需内容 from lxml import html #

我如何做到这一点:

if 'class="*word*"' in html:
    print "True."
else:
    print "False."

要像在Linux中一样使用*作为通配符字符?

您需要查看模块。这将允许您执行正则表达式,并完成与linux命令行中*相同的操作。

您可以使用模块中的正则表达式进行通用模式匹配

但是,如果您使用HTML并尝试匹配标记,我建议您查看并使用其
parse
函数和
cssselect
,以获得所需内容

from lxml import html

# read in and parse the html
html_doc = parse(filename).getroot()

# get elements that match class "classname"
elements = html_doc.cssselect(.classname)

介绍不同的CSS选择器

如果您只想匹配Unix文件名模式匹配,可以使用专用模块:


如果您想进行高级模式匹配,请使用正则表达式。

如果您遵循这一思路,您就会意识到这一点
import fnmatch
words = ["testing", "wildcard", "in", "python"]
filtered = fnmatch.filter(words, 'p?thon')
# filtered = ['python']
filtered = fnmatch.filter(words, 'w*')
# filtered = ['wildcard']