How to check for ANSI character in Python

577 Views Asked by At

I'm trying to validate a set of strings to report out the usage of illegal ANSI characters. I've read that extended ASCII is NOT exactly similar to ANSI. I've been trying to search for a way to check if a character is an ANSI character, but so far I found none. Does anyone know how to do this in Python?

2

There are 2 best solutions below

0
rnso On BEST ANSWER

Try with ord(c) function:

def detect_non_printable(s):
    for c in s: 
        n = ord(c)
        if n < 32 or n > 126: 
           return "NON-PRINTABLE DETECTED" 
    return "PRINTABLE CHARS ONLY"
0
Jules Civel On

This might help you with detecting any ANSI character in a text :

split_ANSI_escape_sequences = re.compile(r"""
    (?P<col>(\x1b     # literal ESC
    \[       # literal [
    [;\d]*   # zero or more digits or semicolons
    [A-Za-z] # a letter
    )*)
    (?P<name>.*)
    """, re.VERBOSE).match

def split_ANSI(s):
    return split_ANSI_escape_sequences(s).groupdict()

Found this code on this question.