Python grep variable

I need something like grep in python I did some research and found a suitable module I need to look for variables for a specific string

+3
source share
3 answers

To find a specific string inside a variable, you can simply use in:

>>> 'foo' in 'foobar'
True
>>> s = 'foobar'
>>> 'foo' in s
True
>>> 'baz' in s
False
+4
source

re.findall . , , ( string in, ), , grep ( , , ).

>>> re.findall("x", "xyz")
['x']
>>> re.findall("b.d", "abcde")
['bcd']
>>> re.findall("a?ba?c", "abacbc")
['abac', 'bc']
+1

, - , , . .

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

. . true grep, if substring in line , re .

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))

, , . , pip install colorama. , , .

+1
source

Source: https://habr.com/ru/post/1792120/


All Articles