Remove ANSI Escape Sequences from a String in Python



You can use regexes to remove the ANSI escape sequences from a string in Python. Simply substitute the escape sequences with an empty string using re.sub(). The regex you can use for removing ANSI escape sequences is: '(\x9B|\x1B\[)[0-?]*[ -\/]*[@-~]'.

For example,

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')
                                 

 This will give the output:

 '\tSomeText                                  172.18.0.2'
Updated on: 2019-09-30T07:34:57+05:30

9K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements