Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

grep variable in python

Tags:

python

grep

I need something like grep in python I have done research and found the re module to be suitable I need to search variables for a specific string

like image 534
jtl999 Avatar asked Jan 20 '23 11:01

jtl999


2 Answers

To search for a specific string within a variable, you can just use in:

>>> 'foo' in 'foobar'
True
>>> s = 'foobar'
>>> 'foo' in s
True
>>> 'baz' in s
False
like image 85
Daniel DiPaolo Avatar answered Jan 31 '23 19:01

Daniel DiPaolo


Using re.findall will be the easiest way. You can search for just a literal string if that's what you're looking for (although your purpose would be better served by the string in operator and you'll need to escape regex characters), or else any string you would pass to grep (although I don't know the syntax differences between the two off the top of my head, but I'm sure there are differences).

>>> re.findall("x", "xyz")
['x']
>>> re.findall("b.d", "abcde")
['bcd']
>>> re.findall("a?ba?c", "abacbc")
['abac', 'bc']
like image 36
user470379 Avatar answered Jan 31 '23 20:01

user470379