pmakal
pmakal

Reputation: 79

Get a sequence of UTF-8 characters in hex from a unicode string

Let's say I have a UTF-8 string:

u"Some String"

Now all I want is to take this string above and convert it into a string of UTF-8 characters but in hex representation, so it will look like this:

"53 6F 6D 65 20 53 74 72 69 6E 67"

How to achive this in Python 2.7?

Upvotes: 2

Views: 914

Answers (1)

Jean-François Fabre
Jean-François Fabre

Reputation: 140256

I would build the string using join and format in a list comprehension, iterating on the characters and taking their code using ord:

s = u"Some String"

print(" ".join(["{:02X}".format(ord(c)) for c in s]))

result:

53 6F 6D 65 20 53 74 72 69 6E 67

notes

  • works both Python 2 and 3
  • if your characters have a code > 255, you may get identifiers with a size greater than 2, but it still works.

Upvotes: 3

Related Questions