Find all items in a list that match a specific format
<p>I am trying to find everything in a list that has an format like "######-##"</p>

<p>I thought I had the right idea in my following code, but it isn't printing anything. Some values in my list have that format, and I would think it should print it. Could you tell me what's wrong?</p>

<pre><code>for line in list_nums:
    if (line[-1:].isdigit()):
        if (line[-2:-1].isdigit()):
            if (line[-6:-5].isdigit()):
                if ("-" in line[-3:-2]):
                    print(list_nums)
</code></pre>

<p>The values in my list consist of formats like 123456-56 and 123456-98-98, which is why what I did above. It is pulled from an excel sheet.</p>

<p><strong>This is my updated code.</strong></p>

<pre><code>import xlrd
from re import compile, match

file_location = "R:/emily/emilylistnum.xlsx"
workbook = xlrd.open_workbook(file_location)
sheet = workbook.sheet_by_index(0)
regexp = compile(r'^\d{d}-\d{2}$')
list_nums = ""


for row in range(sheet.nrows):
    cell = sheet.cell_value(row,0)
    if regexp.match(cell):
        list_nums += cell + "\n"
        print(list_nums)
</code></pre>

<p><strong>my excel sheet consists of:</strong> 
581094-001
581095-001
581096-001
581097-01
5586987-007
SMX53-5567-53BP
552392-01-01
552392-02
552392-03-01
552392-10-01
552392-10-01
580062
580063
580065
580065
580066
543921-01
556664-55</p>

<p>(in each cell down in one column)</p>

<p>Your code seems to be doing the right thing, with the exception that you want it to <strong>print</strong> the value of <em>line</em> instead of the value of <em>list_nums</em>. </p>

<p>Another approach to the task at hand, would be to use regular expressions, which are ideal for pattern recognition.</p>

<p><strong>EDIT: CODE NOW ASSUMES list_nums TO BE A SINGLE STRING</strong> </p>

<pre><code>import re

rx = re.compile('\d{6}-\d{2}\Z')
for line in list_nums.split('\n'):
  if rx.match(line):
    print line
</code></pre>

python loops for-loop