Extracting a string from a text file in python 2.7.5
Question: Hello I am new to python, and I hope you can help me. I have a text file (call
it data.txt) with data on gene number with corresponding rs number and some
distance measure. The data looks something like this:

    
    
       rs1982171     55349     40802
    
       rs6088650     55902     38550
    
       rs1655902     3105      12220
    
       rs1013677     55902      0
    

where the first column is rs number, second column is gene number, and third
column is some distance measure. The data is much bigger, but hopefully the
above gives you an idea of the dataset. What I want to do is find all the rs
numbers that correspond to a certain gene. For example, for the data set
above, gene 55902= {rs6088650, rs1013677}. Ideally, I want my code to find all
rs numbers corresponding to a given gene. Since I am unable to do that now, I
instead wrote a short code that gives the lines that contain the string
"55902" in the data.txt file:

    
    
      import re
      data=open("data.txt","r")
      for line in data:
          line=line.rstrip()
          if re.search("55902",line):
          print line
    

The problem with this code is that the output is something like this:

    
    
        rs6088650    55902     38550
    
        rs1655902    3105      12220
    
        rs1013677    55902     0
    

I want my code to ignore the string "55902" in the rs number. In other words,
I don't my code to output the second line in the above output because the gene
number is not 55902. I would like my output to be :

    
    
           rs6088650     55902   38550
    
           rs1013677     55902   0
    

How can I modify the above code to achieve what I want. Any help would be
appreciated. Thanks in advance.


Answer: You can use [word boundary (`\b`)](http://www.regular-
expressions.info/wordboundaries.html), to match whole word search:

    
    
    >>> import re
    >>> re.search(r"\b55902\b", "rs1655902     3105      12220")
    >>> re.search(r"\b55902\b", "rs6088650     55902     38550")
    <_sre.SRE_Match object at 0x7f82594566b0>
    

* * *
    
    
    if re.search(r"\b55902\b", line):
        ....
    

