Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 881
georgij Avatar asked Dec 18 '12 07:12

georgij


2 Answers

I don't know of any built-in method, but it's fairly easy to do using a comprehension:

import string
printable = string.ascii_letters + string.digits + string.punctuation + ' '
def hex_escape(s):
    return ''.join(c if c in printable else r'\x{0:02x}'.format(ord(c)) for c in s)
like image 71
ecatmur Avatar answered Oct 11 '22 21:10

ecatmur


I'm kind of late to the party, but if you need it for simple debugging, I found that this works:

string = "\n\t\nHELLO\n\t\n\a\17"

procd = [c for c in string]

print(procd)

# Prints ['\n,', '\t,', '\n,', 'H,', 'E,', 'L,', 'L,', 'O,', '\n,', '\t,', '\n,', '\x07,', '\x0f,']

Ugly, but it helped me find non-printable chars in a string.

like image 37
Carcigenicate Avatar answered Oct 11 '22 19:10

Carcigenicate