Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print byte representation of a string?

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.

like image 442
d3nigma Avatar asked Nov 27 '25 04:11

d3nigma


1 Answers

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
like image 98
martineau Avatar answered Nov 29 '25 19:11

martineau



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!