'Python: How to search a value in a log using identifier

So I want to make a program that can grab a numerical value from a log (.txt). Each value is associated with a log identifier. So here is the contents of my log file (named test.txt):

Log:

ID        Key           Value_1 Value_2
f1     time (sec)       1000     2000
f2     # of people       20       31
f3   # tickets written   27       87

So I want to grab the value 27 from ID f3. Is there a way to do this? I have an idea using readlines() and looping line by line until the ID is found but not sure what to do from there. Here's what I have so far:

with open('test.txt') as f:
    data = f.readlines()

for line in data:
    if 'f3' in line:
        # Code to retrieve value 27


Solution 1:[1]

You can use regex

import re

with open('test.txt') as f:
    for line in f:
        if line[0:2] == "f3":
            print(re.search("\d+", line[2:]).group(0))
27

Regex is a string matching tool. The pattern \d+ tells regex to look for at least one digit. So Regex (re) searches line[2:] (2: skips the first 2 letters) and saves all matches (numbers). Then .group(0) fetches the first result. which is 27

Online demo

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1