Explore Courses Blog Tutorials Interview Questions
0 votes
in Python by (12.7k points)
I have a rundown (list) in python for certain strings, and I want to know which thing in the rundown resembles "A1_8301". This "_" implies that can be any char. Is there a snappy method to do that?

On the off chance that I was utilizing SQL, I simply type something like "where x like "A1_8301"

Thank you

1 Answer

0 votes
by (26.4k points)

You can use Regular expression, check the below code:

import re

pattern = re.compile(r'^A1.8301$')

matches = [x for x in yourlist if pattern.match(x)]

This delivers a list of components that match your prerequisites.

  • 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.

Interested to learn python in detail? Come and Join the python course.

Related questions

Browse Categories