Getting hex value of a character
Martin v. Löwis
martin at v.loewis.de
Thu Dec 12 12:27:41 EST 2002
More information about the Python-list mailing list
Thu Dec 12 12:27:41 EST 2002
- Previous message (by thread): Getting hex value of a character
- Next message (by thread): Getting hex value of a character
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
"Dennis Reinhardt" <DennisR at dair.com> writes: > I am trying to print the hexadecimal value of a string. In other words, the > string "AB" would print as "4142". I simply cannot get the formatting > right. [...] > None of the print statements I have tried above work. A common problem to > many is that int cannot convert the argument given. The result I am hoping > for here is "hex = 67". This must be really simple but I am not getting it > and have consulted the indexes of 4 Python books. You should first ask yourself why you think "AB" is related to "4142", and not to, say, "172": >>> 0xAB 171 >>> int("AB",16) 171 >>> "%2x" % int("AB",16) 'ab' That is, of course, because you do not want the hexadecimal value of a string. If you would want that, you had to interpret each digit as a hexadecimal number (allowing only [0-9a-fA-F]). Instead, the relationship is that the ASCII ordinal of "A" is 65, and 65 is hexadecimal 41. Python does not have a function to perform this in one step, so you have to split it in many steps. The key information here is that the ord function returns the ASCII ordinal of a character. Notice it accepts only characters, i.e. strings of length 1. This should be sufficient information to make you proceed (although I fear others will post one-line solutions). If you get stuck, don't hesitate to ask again; likewise, if you find a solution, feel free to post it for us to comment. Regards, Martin
- Previous message (by thread): Getting hex value of a character
- Next message (by thread): Getting hex value of a character
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
More information about the Python-list mailing list