Compare strings in python like the sql "like" (with "%" and "_")
Question:
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?
If I was using SQL, i just type something like “where x like “A1_8301”
Thank you!
Answers:
regular expressions are probably the way to go. IIRC, %
should map to .*
and _
should map to .
.
matcher = re.compile('^A1.8301$')
list_of_string = [s for s in stringlist if matcher.match(s)]
In Python you’d use a regular expression:
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 substring matches; BA1k8301-42
should 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.
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?
If I was using SQL, i just type something like “where x like “A1_8301”
Thank you!
regular expressions are probably the way to go. IIRC, %
should map to .*
and _
should map to .
.
matcher = re.compile('^A1.8301$')
list_of_string = [s for s in stringlist if matcher.match(s)]
In Python you’d use a regular expression:
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 substring matches;BA1k8301-42
should not match, for example. There.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.