2018年8月9日木曜日

開発環境

  • OS: macOS High Sierra - Apple
  • Text Editor: Emacs
  • プログラミング言語: Python3

そんなこと出来たっけ?と気になったので試してみた。

コード(Emacs)

Python 3

#!/usr/bin/env python3

s = "ABCDE"
print(s.encode('hex'))

入出力結果(Terminal, Jupyter(IPython))

$ ./sample.py 
Traceback (most recent call last):
  File "./sample.py", line 4, in <module>
    print(s.encode('hex'))
LookupError: 'hex' is not a text encoding; use codecs.encode() to handle arbitrary codecs
$

という事でエラーに。

もしかしてPython 2.7 なら出来るのかなぁと思って試してみる事に。

入出力結果(Terminal, Jupyter(IPython))

$ python -V
Python 2.7.10
$ python sample.py 
4142434445
$

出来た。という事で、双葉 杏さんの話はpython 2.7での話だったみたい。(という事で、私の勘違い。m(_ _)m)

では、Python 3ではどのようにすればいいか。

コード(Emacs)

Python 3

#!/usr/bin/env python3

# 文字列ではななくbytes
print(b'ABCDE'.hex())

# 文字列からの場合は
h = 'ABCDE'.encode().hex()
print(h)

# 元に戻す(bytes)
b = bytes.fromhex(h)
print(b)

# 元に戻す(str)
s = bytes.fromhex(h).decode()
print(s)

入出力結果(Terminal, Jupyter(IPython))

$ ./sample.py
4142434445
4142434445
b'ABCDE'
ABCDE
$

0 コメント:

コメントを投稿