How can I remove the 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-?]*[ -\/]*[@-~].

Example

Here's how to create a function to remove ANSI escape sequences −

import re

def escape_ansi(line):
    ansi_escape = re.compile(r'(\x9B|\x1B\[)[0-?]*[ -\/]*[@-~]')
    return ansi_escape.sub('', line)

# Test with a string containing ANSI escape sequences
test_string = '\t\u001b[0;35mSomeText\u001b[0m\u001b[0;36m172.18.0.2\u001b[0m'
result = escape_ansi(test_string)
print(repr(result))

The output of the above code is −

'\tSomeText172.18.0.2'

The regex pattern (\x9B|\x1B\[)[0-?]*[ -\/]*[@-~] works by matching the ANSI escape sequence start characters (\x9B or \x1B[) followed by optional parameter characters and finally the command character. This effectively removes all ANSI color codes and formatting sequences from your string.

Updated on: 2026-03-13T20:49:11+05:30

9K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements