【问题标题】:python re.findall() with listpython re.findall() 与列表
【发布时间】:2013-11-06 17:12:57
【问题描述】:

我有一个长字符串(例如 AAAABBBBCCCC),我最终希望找到不同子字符串列表中每个成员的所有重叠项(例如 ['AAA', 'AAB', 'ABB', 'BBB']) .

我在以前的 StackOverflow 帖子中发现了一个非常有用的建议 - string count with overlapping occurrences 但是,使用它我似乎无法以 re.findall() 可以识别它们的方式分配子字符串。这可能是愚蠢的,但我似乎无法弄清楚。 ? 似乎在做一些与往常不同的事情......

>>> string = 'AAAABBBBCCCC'
>>> len(re.findall('(?=AAA)', string))
2
>>> substring = 'AAA'
>>> len(re.findall('(?=substring)', string))
0
>>> substring = "'(?=AAA)'"
>>> len(re.findall(substring, string))
0
>>> #This works, but is not overlapping:
>>> substring = 'AAA'
>>> len(re.findall(substring, string))
1

如有任何建议,我将不胜感激!谢谢!

【问题讨论】:

    标签: python regex python-2.7 findall


    【解决方案1】:

    如果我理解正确,您想分配一个变量并在findall 函数中使用它?

    >>> substring = '(?=AAA)' #or "(?=AAA)"
    >>> len(re.findall(substring, string))
    >>> 2
    

    【讨论】:

    • 是的,就是这样。呸!我想我不需要第二个引号,因为它已经被认为是一个字符串:) 谢谢!
    【解决方案2】:

    看看这是否对你有帮助,你的第 5 行是字符串子字符串而不是变量子字符串。

    import re
    string = 'AAAABBBBCCCC'
    len(re.findall('(?=AAA)', string))
    2
    substring = 'AAA'
    len(re.findall('(?=' + substring + ')', string))
    2
    

    【讨论】:

      猜你喜欢
      • 2010-09-20
      • 2017-03-18
      • 1970-01-01
      • 2012-02-18
      • 2023-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多