Hacker News new | past | comments | ask | show | jobs | submit login

python, decoding and encoding the message

a="53414e544120414e442048495320574f524b53484f50"

"".join([chr(int(a[i:(i+2)],16)) for i in range(0,len(a),2)])

=> 'SANTA AND HIS WORKSHOP'

a = 'SANTA AND HIS WORKSHOP'

"".join([hex(ord(c)) for c in a]).replace('0x','')

=> '53414e544120414e442048495320574f524b53484f50'




An easier version and IMO more true to what's actually going on:

>>> bytes.fromhex('53414e544120414e442048495320574f524b53484f50')

b'SANTA AND HIS WORKSHOP'

>>> b'SANTA AND HIS WORKSHOP'.hex()

'53414e544120414e442048495320574f524b53484f50'


Thanks, nice. bytes.fromhex is really reading bytes from a hex string, so perhaps a better name should be bytes.fromhexstring, but since python names are short I understand the trade-off. Also, my first impression is that hex should be called bytes.tohexstring, but for those using python daily I understand the need of shorter names.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: