首页 文章

python正则表达式错误

提问于
浏览
0

我正在尝试进行模式搜索,如果匹配则在计数器值上设置一个bitarray .

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

出现以下错误:

如果re.search(r'dev_router',this_line):2016-07-15T16:27:13:%错误:文件“/auto/pysw/cel55/python/3.4.1/lib/python3.4/re . py“,第166行,在搜索2016-07-15T16:27:13:%-ERROR:return _compile(pattern,flags).search(string)2016-07-15T16:27:13:%-ERROR:TypeError:期望字符串或缓冲区

1 回答

  • 2

    你混淆了enumerate()的参数 - 首先是索引,然后是项目本身 . 更换:

    for this_line,counter in enumerate(runOutput):
    

    有:

    for counter, this_line in enumerate(runOutput):
    

    在这种情况下,你得到一个 TypeError ,因为 this_line 是一个整数,re.search()期望一个字符串作为第二个参数 . 展示:

    >>> 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
    

    顺便说一句,像PyCharm这样的现代IDE可以静态地检测到这种问题:

    enter image description here

    (此屏幕截图使用Python 3.5)

相关问题