比较python中的字符串,如sql“like”(带有“%”和“
我在Python中有一些列表,并且我需要知道列表中的女巫项目是“A1_8301”。 这个“_”意味着可以是任何字符。 有没有快速的方法来做到这一点?
如果我使用的是SQL,我只需键入“where x like”A1_8301“
谢谢!
在Python中你可以使用正则表达式:
import re
pattern = re.compile(r'^A1.8301$')
matches = [x for x in yourlist if pattern.match(x)]
这会生成符合您要求的元素列表。
^和$锚来防止子串匹配; 例如, BA1k8301-42不应该匹配。 re.match()调用只会在测试字符串的起始处匹配,但使用^可以更清晰地显示出来,并很好地反映字符串尾部的$ 。 _被转换为. ,意思是匹配一个字符。 正则表达式可能是要走的路。 IIRC, %应映射到.*和_应映射到. 。
matcher = re.compile('^A1.8301$')
list_of_string = [s for s in stringlist if matcher.match(s)]
链接地址: http://www.djcxy.com/p/55061.html
上一篇: Compare strings in python like the sql "like" (with "%" and "
下一篇: Is it possible to document fields in a record in clojure?
