Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Python string to its ASCII representants

Tags:

python

How do I convert a string in Python to its ASCII hex representants?

Example: I want to result '\x00\x1b\xd4}\xa4\xf3\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' in 001bd47da4f3.

like image 705
Manuel Faux Avatar asked Oct 03 '10 16:10

Manuel Faux


People also ask

Which function is used to convert string to ASCII in Python?

Python ascii() Function The ascii() function returns a readable version of any object (Strings, Tuples, Lists, etc). The ascii() function will replace any non-ascii characters with escape characters: å will be replaced with \xe5 .


1 Answers

>>> text = '\x00\x1b\xd4}\xa4\xf3\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'.rstrip('\0')
>>> print "".join("%02x" % ord(c) for c in text)
001bd47da4f3

As per martineau's comment, here is the Python 3 way:

>>> "".join(format(ord(c),"02x") for c in text)
like image 65
Ryan Ginstrom Avatar answered Sep 29 '22 09:09

Ryan Ginstrom