## DEV Community is a community of 617,294 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

# Python バイト型 bytes

maru3kaku4kaku Originally published at marusankakusikaku.jp ・1 min read

Pythonの組み込み型bytesはバイトのイミュータブルなシーケンスです。

## bytesの定義

``````b = b'abcde' # => b'abcde'
b = b"abcde" # => b'abcde'
b = b"""abcde""" # => b'abcde'
b = b'''abcde''' # => b'abcde'
b = bytes(5) # => b'\x00\x00\x00\x00\x00'
b = bytes( x + 97 for x in range(5)) # => b'abcde'
b = bytes(b"abcde") # => b'abcde'
b = bytes("abcde", "utf-8") # => b'abcde'
``````

## bytes.fromhex(string) 16進数2桁表記文字列をbytesに変換

``````bytes.fromhex("61 62 63") # => b'abc'
``````

## hex([sep[, bytes_per_sep]]) bytesを16進数文字列に変換

``````b = b"abcdefghijk"
b.hex() # => '6162636465666768696a6b'
b.hex('-') # => '61-62-63-64-65-66-67-68-69-6a-6b'
b.hex('-', 4) # => '616263-64656667-68696a6b'
``````

## 整数の配列への変換

``````b = b"abcde"
list(b) # => [97, 98, 99, 100, 101]
``````

## bytesのメソッド

その他stringと同様のメソッドが使えます。