4

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

2
  • 9
    Nice to know. Do you happen to have a question about it? Commented Feb 15, 2011 at 0:04
  • Have you worked through the Python tutorial? Commented Feb 15, 2011 at 0:08

3 Answers 3

6

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
Sign up to request clarification or add additional context in comments.

Comments

3

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']

Comments

1

It sounds like what you really want is the ability to print a large substring in a way that lets you easily see where a particular substring is. There are a couple of ways to approach this.

def grep(large_string, substring):
    for line, i in enumerate(large_string.split('\n')):
        if substring in line:
            print("{}: {}".format(i, line))

This would print only the lines that have your substring. However, you would lose a bunch of context. If you want true grep, replace if substring in line with something that uses the re module to do regular expression matching.

def highlight(large_string, substring):
    from colorama import Fore
    text_in_between = large_string.split(substring)
    highlighted_substring = "{}{}{}".format(Fore.RED, substring, Fore.RESET)
    print(highlighted_substring.join(text_in_between))

This will print the whole large string, but with the substring you are looking for in red. Note that you'll need to pip install colorama for it to work. You can of course combine the two approaches.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.