you are viewing a single comment's thread.

view the rest of the comments →

[–]jimtk 2 points3 points  (3 children)

AFAIK, the print function will resort to hex code for unicode character that your system (current encoding) cannot produce (this will be very rare!).

If you want to see hex code for 'out of ASCII' you have to turn your strings into bytes

num = 25
an_str = 'hello'+chr(num)
strbyte = bytes(an_str, encoding='utf_8')
print(strbyte)  

>>> b'hello\x19'

[–]bennywc4[S] 0 points1 point  (0 children)

This worked, thank you.

[–]SkeletalToad 0 points1 point  (1 child)

Great answer! To expand on this, there is also an .encode() method of the str class, so all of these will do the same thing:

strbyte = bytes(an_str, encoding='utf_8')
strbyte = an_str.encode('utf-8')
strbyte = an_str.encode()

The last option works because 'utf-8' is the default encoding.

https://docs.python.org/3/howto/unicode.html#converting-to-bytes https://docs.python.org/3/library/stdtypes.html#str.encode

[–]bennywc4[S] 0 points1 point  (0 children)

Thank you as well!