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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With