'Complement maketrans in python for translate

For translating tr in perl to python, I am using string.maketrans and str.translate. However, for the perl expression:

$val =~ tr/\0-\377//c

The user is asking for the complement of the translation. How I generate python code for that?



Solution 1:[1]

I assume you want to delete characters not int the range of ordinal values [0-255], then you could simply do

val = "".join([ch for ch in val if 0o000 <= ord(ch)<= 0o377])

Solution 2:[2]

Here is what I implemented in perllib:

def _maketrans_c(arg1, arg2, delete=False):
    """Make a complement tr table for the 'c' flag.  If the 'd' flag is passed, then delete=True.  Ranges are expanded in arg1 and arg2 but arg2 is not otherwise normalized"""
    t = str.maketrans(arg1, arg1)
    d = dict()
    for i in range(257):
        if i not in t:
            if not arg2:
                if delete:
                    d[i] = None
                else:
                    d[i] = i
            elif i < len(arg2):
                d[i] = arg2[i]
            elif delete:
                d[i] = None
            else:
                d[i] = arg2[-1]

    return str.maketrans(d)


def _translate_and_count(table, var, replace=True, complement=False, delete=False, squash=False):
    """Perform a tr translate, but also count the # of matches"""
    result = []
    ctr = 0;
    pv = None
    for ch in var:
        if ord(ch) > 256 and complement:
            ch = chr(256)
        try:
            v = table[ord(ch)]
            ctr += 1
        except LookupError:
            v = ch
            pv = None
        if v is not None:
            if isinstance(v, int):
                v = chr(v)
            if pv != v or not squash:
                result.append(v)
        pv = v
    if not replace:
        return (var, ''.join(result))
    return (''.join(result), ctr)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Håkon Hægland
Solution 2 snoopyjc