如何從 Python 字串中移除 ANSI 轉義序列?
可以使用正則表示式來從 Python 字串中移除 ANSI 轉義序列。使用 re.sub() 將轉義序列替換為空字串即可。可用於移除 ANSI 轉義序列的正則表示式為:'(\x9B|\x1B\[)[0-?]*[ -\/]*[@-~]'。
例如,
import re def escape_ansi(line): ansi_escape =re.compile(r'(\x9B|\x1B\[)[0-?]*[ -\/]*[@-~]') return ansi_escape.sub('', line) print escape_ansi(line = '\t\u001b[0;35mSomeText\u001b[0m\u001b[0;36m172.18.0.2\u001b[0m')
將輸出
'\tSomeText 172.18.0.2'
廣告