So I have a string like "abcd"
and I want to convert it into bytes and print it.
I tried print(b'abcd')
which prints exactly b'abcd'
but I want '\x61\x62\x63\x64'
.
Is there a single function for this purpose or do I have to use unhexlify with join?
Note: This is a simplified example of what I'm acutally doing. I need the aforementioned representation for a regex search.
CodePudding user response:
There's no single function to do it, so you would need to do the formatting manually:
s = 'abcd'
print(r'\x' r'\x'.join(f'{b:02x}' for b in bytes(s, 'utf8')))
Output:
\x61\x62\x63\x64
CodePudding user response:
You can get hex values of a string like this:
string = "abcd"
print(".".join(hex(ord(c))[2:] for c in string))