Python で文字列をバイトに変換する方法

Python 3 で文字列をバイトに変換するメソッドを紹介します。
bytes
コンストラクターメソッドstr.encode
方法
bytes
データ型 は Python 3 から導入された組み込み型であり、Python 2.x では bytes
実際に string
型であるため、Python 2.x でこの変換は必要ありません。
bytes
文字列をバイトに変換するコンストラクタ
bytes
クラスコンストラクターは、文字列 string
などのデータからバイトの配列を構築します。
bytes(string, encoding)
encoding
引数を指定する必要があります。指定しない場合、TypeError
が発生します。
>>> bytes("Test", encoding = "utf-8")
b'Test'
>>> bytes("Test")
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
bytes("Test")
TypeError: string argument without an encoding
str.encode
文字列をバイトに変換するコンストラクタ
str.encode(encoding=)
string
クラスの encode
メソッドは、文字列をバイトに変換することもできます。上記の方法と比較して、必要な encoding
が utf-8
の場合、encoding
パラメーターを指定する必要がないという利点があります。
>>> test = "Test"
>>> test.encode()
b'Test'
>>> test.encode(encoding="utf-8")
b'Test'
Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.
LinkedIn関連記事 - Python Bytes
- Python バイトを整数に変換する方法
- Python 2 および Python 3 で Int をバイトに変換する方法
- Python で Int をバイナリに変換する方法
- Python 2 および Python 3 でバイトを文字列に変換する方法
- Python で文字列の前に B をつける
関連記事 - Python String
- Python で文字列からコンマを削除する
- Pythonic 方式で文字列が空であることを確認する方法
- Python で文字列を変数名に変換する
- Python 文字列の空白を削除する方法
- Python で文字列から数字を抽出する
- Python が文字列を日時 datetime に変換する方法