Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีลบ ANSI Escape Sequences ออกจาก String ใน Python

ใช้ regex กับ re.sub() แทนที่ escape sequences ด้วยสตริงว่าง

Regex pattern

r'(\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('\t\u001b[0;35mSomeText\u001b[0m\u001b[0;36m172.18.0.2\u001b[0m'))

ผลลัพธ์

'\tSomeText 172.18.0.2'