python difflib

pythonのdifflibの概要と使い方

タグ difflib


pythonのdifflibの概要と使い方

概要

  • gitのdiffのようなものをpythonで行えるもの
  • デフォルトライブラリ

使い方

import difflib

def get_diff(text1, text2):
    d = difflib.Differ()
    diff = list(d.compare(text1.splitlines(), text2.splitlines()))
    return '\n'.join(diff)

text1 = """apple
banana
cherry
date"""

text2 = """apple
berry
cherry
date
elderberry"""

print(get_diff(text1, text2))
"""
  apple
- banana
+ berry
  cherry
  date
+ elderberry
"""

Google Colab

参考