pythonpython-3.xescaping

Show non printable characters in a string


Is it possible to visualize non-printable characters in a python string with its hex values?

e.g. If I have a string with a newline inside I would like to replace it with \x0a.

I know there is repr() which will give me ...\n, but I'm looking for the hex version.


Solution

  • You'll have to make the translation manually; go through the string with a regular expression for example, and replace each occurrence with the hex equivalent.

    import re
    
    replchars = re.compile(r'[\n\r]')
    def replchars_to_hex(match):
        return r'\x{0:02x}'.format(ord(match.group()))
    
    replchars.sub(replchars_to_hex, inputtext)
    

    The above example only matches newlines and carriage returns, but you can expand what characters are matched, including using \x escape codes and ranges.

    >>> inputtext = 'Some example containing a newline.\nRight there.\n'
    >>> replchars.sub(replchars_to_hex, inputtext)
    'Some example containing a newline.\\x0aRight there.\\x0a'
    >>> print(replchars.sub(replchars_to_hex, inputtext))
    Some example containing a newline.\x0aRight there.\x0a