Python の組み込み関数 bytes の使い方です。
bytes 関数を使用したコード例と、実行結果を載せました。
Python マニュアルによると、1 バイトは 8-bit とのことでした。
bytes オブジェクトは不変な配列です。要素は
8-bit
バイトで、0 <= x < 256
の範囲の整数で表現されます。(Python)
bytes
(Python 言語リファレンス ⇒ 標準型の階層 ⇒ シーケンス型 ⇒ 変更不能なシーケンス)
bytes 関数を使用したら、以下のことができました。
- 『0 から 255 までの int のリスト』から、バイト列 (bytes) を作ることができました。
- 『バイト列 (bytes)』または『バイトアレイ (bytearray)』を渡して、バイト列 (bytes) を得ることができました。
- 『文字列 (str)』をエンコードして、バイト列 (bytes) に変換することができました。
あと、『エラーになったコード例』も一緒に載せました。
エラーになったコード例
bytes 関数で、エラーになったコード例です。
(Python) class bytes([source[, encoding[, errors]]])
bytes(None) # None
TypeError: cannot convert 'NoneType' object to bytes
bytes('1') # '1'
TypeError: string argument without an encoding
bytes(['1']) # ['1']
TypeError: 'str' object cannot be interpreted as an integer
bytes('\x01') # '\x01'
TypeError: string argument without an encoding
bytes(['\x01']) # ['\x01']
TypeError: 'str' object cannot be interpreted as an integer
bytes(1.2) # 1.2
TypeError: cannot convert 'float' object to bytes
bytes([1.2]) # [1.2]
TypeError: 'float' object cannot be interpreted as an integer
bytes(complex(3, 4)) # (3+4j)
TypeError: cannot convert 'complex' object to bytes
bytes([complex(3, 4)]) # [(3+4j)]
TypeError: 'complex' object cannot be interpreted as an integer
引数無しで実行した結果
bytes 関数を、引数無しで実行した結果です。
(Python) class bytes([source[, encoding[, errors]]])
bytes() # 引数無し
b''
組み込み定数を渡した結果
bytes 関数に、組み込み定数を渡した結果です。
(Python) class bytes([source[, encoding[, errors]]])
bytes(False) # False
b''
bytes(True) # True
b'\x00'
bytes([False, False, True, True]) # [False, False, True, True]
b'\x00\x00\x01\x01'
int を渡した結果
bytes 関数に、int(整数)を渡した結果です。
(Python) class bytes([source[, encoding[, errors]]])
bytes(-1) # -1
ValueError: negative count
bytes(0) # 0
b''
bytes(1) # 1
b'\x00'
bytes(2) # 2
b'\x00\x00'
bytes(3) # 3
b'\x00\x00\x00'
int の tuple を渡した結果
bytes 関数に、int(整数)の tuple を渡した結果です。
(Python) class bytes([source[, encoding[, errors]]])
bytes(()) # () 空のタプル
b''
bytes((-1,)) # (-1,)
ValueError: bytes must be in range(0, 256)
bytes((0,)) # (0,)
b'\x00'
bytes((1,)) # (1,)
b'\x01'
bytes((255,)) # (255,)
b'\xff'
bytes((256,)) # (256,)
ValueError: bytes must be in range(0, 256)
bytes((0, 1, 254, 255)) # (0, 1, 254, 255)
b'\x00\x01\xfe\xff'
int の list を渡した結果
bytes 関数に、int(整数)の list を渡した結果です。
(Python) class bytes([source[, encoding[, errors]]])
(Python) class list([iterable])
bytes([]) # [] 空のリスト
b''
bytes([-1]) # [-1]
ValueError: bytes must be in range(0, 256)
bytes([0]) # [0]
b'\x00'
bytes([1]) # [1]
b'\x01'
bytes([255]) # [255]
b'\xff'
bytes([256]) # [256]
ValueError: bytes must be in range(0, 256)
bytes([0, 1, 254, 255]) # [0, 1, 254, 255]
b'\x00\x01\xfe\xff'
int の set を渡した結果
bytes 関数に、int(整数)の set(集合) を渡した結果です。
(Python) class bytes([source[, encoding[, errors]]])
(Python) class set([iterable])
bytes(set()) # set() 空の集合
b''
bytes({-1}) # {-1}
ValueError: bytes must be in range(0, 256)
bytes({0}) # {0}
b'\x00'
bytes({1}) # {1}
b'\x01'
bytes({255}) # {255}
b'\xff'
bytes({256}) # {256}
ValueError: bytes must be in range(0, 256)
bytes({0, 1, 254, 255}) # {0, 1, 254, 255}
b'\x00\x01\xfe\xff'
int の dict を渡した結果
bytes 関数に、int(整数)の dict(辞書) を渡した結果です。
(Python) class bytes([source[, encoding[, errors]]])
bytes({}) # {} 空の辞書
b''
bytes({-1: None}) # {-1: None}
ValueError: bytes must be in range(0, 256)
bytes({0: None}) # {0: None}
b'\x00'
bytes({1: None}) # {1: None}
b'\x01'
bytes({255: None}) # {255: None}
b'\xff'
bytes({256: None}) # {256: None}
ValueError: bytes must be in range(0, 256)
bytes({0: 7, 255: 8}) # {0: 7, 255: 8}
b'\x00\xff'
bytes({0: 7, 255: 8}.keys()) # dict_keys([0, 255])
b'\x00\xff'
bytes({0: 7, 255: 8}.values()) # dict_values([7, 8])
b'\x07\x08'
bytes({0: 7, 255: 8}.items()) # dict_items([(0, 7), (255, 8)])
TypeError: 'tuple' object cannot be interpreted as an integer
range を渡した結果
bytes 関数に、range を渡した結果です。
(Python) class bytes([source[, encoding[, errors]]])
(Python) range(start, stop[, step])
bytes(range(0)) # range(0, 0)
b''
bytes(range(1)) # range(0, 1)
b'\x00'
bytes(range(5)) # range(0, 5)
b'\x00\x01\x02\x03\x04'
bytes(range(2, 5)) # range(2, 5)
b'\x02\x03\x04'
bytes(range(0, 6, 2)) # range(0, 6, 2)
b'\x00\x02\x04'
bytes(range(6, 0, -2)) # range(6, 0, -2)
b'\x06\x04\x02'
bytes を渡した結果
bytes 関数に、bytes を渡した結果です。
(Python) class bytes([source[, encoding[, errors]]])
bytes(b'') # b'' 空のバイト列
b''
bytes(b'\x08') # b'\x08'
b'\x08'
bytes(b'8') # b'8'
b'8'
bytes(b'\x09') # b'\t'
b'\t'
bytes(b'9') # b'9'
b'9'
bytes(b'\x08\x09\x10\x11') # b'\x08\t\x10\x11'
b'\x08\t\x10\x11'
bytes(b'a') # b'a'
b'a'
bytes(b'9a') # b'9a'
b'9a'
(Python) str.encode(encoding="utf-8", errors="strict")
bytes('9aあ'.encode('utf-8')) # b'9a\xe3\x81\x82'
b'9a\xe3\x81\x82'
bytearray を渡した結果
bytes 関数に、bytearray を渡した結果です。
(Python) class bytearray([source[, encoding[, errors]]])
bytes(bytearray(b'')) # bytearray(b'')
b''
bytes(bytearray(b'\x08')) # bytearray(b'\x08')
b'\x08'
bytes(bytearray(b'8')) # bytearray(b'8')
b'8'
bytes(bytearray(b'\x09')) # bytearray(b'\t')
b'\t'
bytes(bytearray(b'9')) # bytearray(b'9')
b'9'
bytes(bytearray(b'\x08\x09\x10\x11')) # bytearray(b'\x08\t\x10\x11')
b'\x08\t\x10\x11'
bytes(bytearray(b'a')) # bytearray(b'a')
b'a'
bytes(bytearray(b'9a')) # bytearray(b'9a')
b'9a'
(Python) str.encode(encoding="utf-8", errors="strict")
bytes(bytearray('9aあ'.encode('utf-8'))) # bytearray(b'9a\xe3\x81\x82')
b'9a\xe3\x81\x82'
文字列 (str)
bytes 関数に、普通の文字列 (str) を渡した結果です。
英数字と記号だけの『ASCII 文字列』を渡した場合と、日本語などの『非 ASCII 文字列』を渡した場合を書きました。
ASCII 文字列 を渡した結果
bytes 関数に、ASCII 文字列を渡した結果です。
(Python) class bytes([source[, encoding[, errors]]])
(Python) 標準エンコーディング ('ascii', 'utf-8', ...
)
bytes('abc123+-*/#', encoding='utf-8')
b'abc123+-*/#'
bytes('a', encoding='utf-8')
b'a'
bytes('a', encoding='utf-8-sig')
b'\xef\xbb\xbfa'
bytes('a', encoding='utf-16')
b'\xff\xfea\x00'
bytes('a', encoding='utf-32')
b'\xff\xfe\x00\x00a\x00\x00\x00'
bytes('a', encoding='shift-jis')
b'a'
bytes('a', encoding='ascii')
b'a'
非 ASCII 文字列 を渡した結果(日本語など)
bytes 関数に、『非 ASCII 文字列』を渡した結果です。
指定した encoding でエンコードが失敗したときは、errors の内容に応じて、結果が変わりました。
(Python) class bytes([source[, encoding[, errors]]])
(Python) 標準エンコーディング ('ascii', 'utf-8', ...
)
(Python) エラーハンドラ ('strict', 'ignore', 'replace', ...
)
bytes('あいう123+-*/#', encoding='utf-8')
b'\xe3\x81\x82\xe3\x81\x84\xe3\x81\x86123+-*/#'
bytes('あ', encoding='utf-8')
b'\xe3\x81\x82'
bytes('あ', encoding='utf-8-sig')
b'\xef\xbb\xbf\xe3\x81\x82'
bytes('あ', encoding='utf-16')
b'\xff\xfeB0'
bytes('あ', encoding='utf-32')
b'\xff\xfe\x00\x00B0\x00\x00'
bytes('あ', encoding='shift-jis')
b'\x82\xa0'
bytes('あ', encoding='ascii')
UnicodeEncodeError: 'ascii' codec can't encode character '\u3042' in position 0: ordinal not in range(128)
bytes('あ', encoding='ascii', errors='strict')
UnicodeEncodeError: 'ascii' codec can't encode character '\u3042' in position 0: ordinal not in range(128)
bytes('あ', encoding='ascii', errors='ignore')
b''
bytes('あ', encoding='ascii', errors='replace')
b'?'
bytes('あ', encoding='ascii', errors='xmlcharrefreplace')
b'あ'
bytes('あ', encoding='ascii', errors='backslashreplace')
b'\\u3042'
bytes('あ', encoding='ascii', errors='namereplace')
b'\\N{HIRAGANA LETTER A}'
bytes('あ', encoding='ascii', errors='surrogateescape')
UnicodeEncodeError: 'ascii' codec can't encode character '\u3042' in position 0: ordinal not in range(128)
bytes('あ', encoding='ascii', errors='surrogatepass')
UnicodeEncodeError: 'ascii' codec can't encode character '\u3042' in position 0: ordinal not in range(128)
以上です。