Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Re: how to get character hex number?

82 views
Skip to first unread message

Ian Kelly

unread,
Aug 31, 2012, 10:40:32 PM8/31/12
to Python
On Fri, Aug 31, 2012 at 8:21 PM, contro opinion <contro...@gmail.com> wrote:
>>>> for i in "english" :
> ... print(hex((ord(i))))
> ...
> 0x65
> 0x6e
> 0x67
> 0x6c
> 0x69
> 0x73
> 0x68
>>>> u"english".encode("utf-8")
> 'english'
>>>> u"english".encode("ascii")
> 'english'
>
> how can i get 656e676c697368 in encode method?

>>> ''.join("%02x" % ord(b) for b in u"english".encode("ascii"))
'656e676c697368'

Tim Chase

unread,
Aug 31, 2012, 10:42:57 PM8/31/12
to contro opinion, python-list
On 08/31/12 21:21, contro opinion wrote:
>>>> for i in "english" :
> ... print(hex((ord(i))))
> ...
> 0x65
> 0x6e
> 0x67
> 0x6c
> 0x69
> 0x73
> 0x68
>>>> u"english".encode("utf-8")
> 'english'
>>>> u"english".encode("ascii")
> 'english'
>
> how can i get 656e676c697368 in encode method?

At least in 2.x, you can do:

>>> u"english".encode("hex")
'656e676c697368'

-tkc



Tim Chase

unread,
Aug 31, 2012, 11:50:33 PM8/31/12
to Python
On 08/31/12 22:41, contro opinion wrote:
>>>>>> u"english".encode("utf-8")
>>> 'english'
>>>>>> u"english".encode("ascii")
>>> 'english'
>>>
>>> how can i get 656e676c697368 in encode method?
>>
>> At least in 2.x, you can do:
>>
>> >>> u"english".encode("hex")
>> '656e676c697368'
>
> how about in python3.0?

Well, in 3.1.3 at least, using the u"..." notation dies on me with
an invalid syntax. However, as Ian suggests, you can do

my_str = "english"
"".join("%02x" % c for c in my_str.encode("ascii"))

or whatever other encoding you want instead of "ascii".

-tkc


Peter Otten

unread,
Sep 1, 2012, 2:37:00 AM9/1/12
to pytho...@python.org
Another option:

>>> binascii.hexlify("english".encode()).decode()
'656e676c697368'


Mark Lawrence

unread,
Sep 1, 2012, 4:49:39 AM9/1/12
to pytho...@python.org
On 01/09/2012 04:50, Tim Chase wrote:
>
> Well, in 3.1.3 at least, using the u"..." notation dies on me with
> an invalid syntax. However, as Ian suggests, you can do
>
> my_str = "english"
> "".join("%02x" % c for c in my_str.encode("ascii"))
>
> or whatever other encoding you want instead of "ascii".
>
> -tkc
>
>

The u"..." notation has been reintroducd for Python 3.3 see
http://docs.python.org/dev/whatsnew/3.3.html#pep-414-explicit-unicode-literals

--
Cheers.

Mark Lawrence.

Tim Chase

unread,
Sep 1, 2012, 7:48:51 AM9/1/12
to Mark Lawrence, pytho...@python.org
On 09/01/12 03:49, Mark Lawrence wrote:
> On 01/09/2012 04:50, Tim Chase wrote:
>> Well, in 3.1.3 at least, using the u"..." notation dies on me with
>> an invalid syntax.
>
> The u"..." notation has been reintroducd for Python 3.3

Nice to know--it makes writing backwards compat. code just a bit
easier, even if it is a NOOP. I'll catch it when Debian Stable
makes it there (currently at 3.1).

-tkc


0 new messages