How can I remove the ANSI escape sequences from a string in python?

PythonServer Side ProgrammingProgramming

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'
raja
Published on 14-Dec-2017 06:10:55
Advertisements