Python - how to find all intersections of two strings?

前端 未结 6 1692
花落未央
花落未央 2021-02-04 18:21

How to find all intersections (also called the longest common substrings) of two strings and their positions in both strings?

For example, if S1=\"never\"

6条回答
  •  不思量自难忘°
    2021-02-04 19:09

    Batteries included!

    The difflib module might have some help for you - here is a quick and dirty side-by-side diff:

    >>> import difflib
    >>> list(difflib.ndiff("never","forever"))
    ['- n', '+ f', '+ o', '+ r', '  e', '  v', '  e', '  r']
    >>> diffs = list(difflib.ndiff("never","forever"))
    >>> for d in diffs:
    ...   print {' ': '  ', '-':'', '+':'    '}[d[0]]+d[1:]
    ...
     n
         f
         o
         r
       e
       v
       e
       r
    

提交回复
热议问题