python regular expression error
Question: I am trying do a pattern search and if match then set a bitarray on the
counter value.

    
    
    runOutput = device[router].execute (cmd)
                runOutput = output.split('\n')
                print(runOutput)
                for this_line,counter in enumerate(runOutput):
                    print(counter)
                    if  re.search(r'dev_router', this_line) :
                        #want to use the counter to set something
    

Getting the following error:

> if re.search(r'dev_router', this_line) :
>
> 2016-07-15T16:27:13: %ERROR: File
> "/auto/pysw/cel55/python/3.4.1/lib/python3.4/re.py", line 166,
>
> in search 2016-07-15T16:27:13: %-ERROR: return _compile(pattern,
> flags).search(string)
>
> 2016-07-15T16:27:13: %-ERROR: TypeError: expected string or buffer


Answer: You mixed up the arguments for
[`enumerate()`](https://docs.python.org/2/library/functions.html#enumerate) \-
first goes the index, then the item itself. Replace:

    
    
    for this_line,counter in enumerate(runOutput):
    

with:

    
    
    for counter, this_line in enumerate(runOutput):
    

* * *

You are getting a `TypeError` in this case because `this_line` is an integer
and [`re.search()`](https://docs.python.org/2/library/re.html#re.search)
expects a string as a second argument. To demonstrate:

    
    
    >>> import re
    >>>
    >>> this_line = 0
    >>> re.search(r'dev_router', this_line)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "/Users/user/.virtualenvs/so/lib/python2.7/re.py", line 146, in search
        return _compile(pattern, flags).search(string)
    TypeError: expected string or buffer
    

* * *

By the way, modern IDEs like [PyCharm](https://www.jetbrains.com/pycharm/) can
detect this kind of problems statically:

[![enter image description
here](http://i.stack.imgur.com/q1uFa.png)](http://i.stack.imgur.com/q1uFa.png)

(Python 3.5 is used for this screenshot)

