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

Jinku Hu 2023年1月30日 2020年1月1日
  1. bytes 文字列をバイトに変換するコンストラクタ
  2. str.encode 文字列をバイトに変換するコンストラクタ
Python で文字列をバイトに変換する方法

Python 3 で文字列をバイトに変換するメソッドを紹介します。

  1. bytes コンストラクターメソッド
  2. 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 メソッドは、文字列をバイトに変換することもできます。上記の方法と比較して、必要な encodingutf-8 の場合、encoding パラメーターを指定する必要がないという利点があります。

>>> test = "Test"
>>> test.encode()
b'Test'
>>> test.encode(encoding="utf-8")
b'Test'
Author: Jinku Hu
Jinku Hu avatar Jinku Hu avatar

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 String