Python I/O and string matching
Question: I realize this is probably really easy, I want the equivalent of this C code
in Python:

    
    
    #include <stdio.h>
    #include <string.h>
    #define BUFFER 200
    int main()
    {
        char buffer[BUFFER];
        while (fgets(buffer, BUFFER, stdin))
        {
            if (strstr(buffer, "BEER"))
                printf("Drink up!\n");
        }
        return 0;
    }
    

I searched on the web, but I think my brain is fried.


Answer: The Pythonic thing to do is a little different:

    
    
    import fileinput
    for line in fileinput.input():
        if "BEER" in line:
            print("Drink up!")
    

But that does a whole lot of things your C code doesn't do, like allowing the
user to pass filename arguments to be read in place of stdin as arguments,
etc.

* * *

This is a more direct mapping of your code:

    
    
    try:
        while True:
            buffer = input() # or raw_input, for 2.x
            if "BEER" in buffer:
                print("Drink up!")
    except EOFError:
        pass
    

However, it's missing the part where a line more than 300-character line that
includes `"BEER"` in the first 200 characters and then again in the next will
print twice, or a 300-character line that has "BEER" starting at position 198
won't print it at all.

* * *

If that's a problem, you probably want something like this:

    
    
    import sys
    
    while True:
        buffer = sys.stdin.readlines(200)
        if not buffer:
            break
        for line in buffer:
            for i in range(0, len(buffer), 200):
                if "BEER" in buffer[i*200:i*200+200]:
                    print("Drink up!")
    

