比较python中的字符串,如sql“like”(带有“%”和“_”)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26148712/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:09:31  来源:igfitidea点击:

Compare strings in python like the sql "like" (with "%" and "_")

pythonstring

提问by Antonio

I have a list in python with some strings, and I need to know witch item in the list is like "A1_8301". This "_" means that can be any char. Is there a quick way to do that?

我在 python 中有一个带有一些字符串的列表,我需要知道列表中的女巫项目就像“A1_8301”。这个“_”表示可以是任何字符。有没有一种快速的方法来做到这一点?

If I was using SQL, i just type something like "where x like "A1_8301"

如果我使用的是 SQL,我只需输入类似“where x like “A1_8301”之类的内容

Thank you!

谢谢!

采纳答案by Martijn Pieters

In Python you'd use a regular expression:

在 Python 中,您将使用正则表达式:

import re

pattern = re.compile(r'^A1.8301$')
matches = [x for x in yourlist if pattern.match(x)]

This produces a list of elements that match your requirements.

这将生成符合您要求的元素列表。

  • The ^and $anchors are needed to prevent substringmatches; BA1k8301-42should not match, for example. The re.match()call will only match at the start of the tested string, but using ^makes this a little more explicit and mirrors the $for the end-of-string anchor nicely.
  • The _in a SQL like is translated to ., meaning match one character.
  • ^$需要锚,防止匹配; BA1k8301-42例如,不应该匹配。的re.match()通话将只匹配在测试字符串的开头,但使用^使得这个一点更加明确和镜子$的结束串锚很好。
  • _SQL like 中的 翻译为.,意思是匹配一个字符

回答by mgilson

regular expressions are probably the way to go. IIRC, %should map to .*and _should map to ..

正则表达式可能是要走的路。IIRC,%应该映射到.*并且_应该映射到..

matcher = re.compile('^A1.8301$')
list_of_string = [s for s in stringlist if matcher.match(s)]