Pythonの文字列のエンコードとデコードには、encode()とdecode()メソッドがあります。

Pythonの文字列のencode()メソッド

Pythonのstring encode()関数は、指定されたエンコードを使用して文字列をエンコードするために使用されます。この関数はバイトオブジェクトを返します。もしエンコードを指定しない場合、デフォルトで「utf-8」エンコーディングが使用されます。

Pythonのバイトコードをdecode()する。

Pythonのbytesのdecode()関数は、バイトを文字列オブジェクトに変換するために使用されます。これらの関数の両方は、エンコーディング/デコーディングエラーに対して使用するエラーハンドリングスキームを指定することができます。デフォルトは「strict」で、エンコーディングエラーがUnicodeEncodeErrorを発生させることを意味します。他の可能な値には「ignore」、「replace」、「xmlcharrefreplace」などがあります。Python文字列のencode()とdecode()関数の単純な例を見てみましょう。

str_original = 'Hello'

bytes_encoded = str_original.encode(encoding='utf-8')
print(type(bytes_encoded))

str_decoded = bytes_encoded.decode()
print(type(str_decoded))

print('Encoded bytes =', bytes_encoded)
print('Decoded String =', str_decoded)
print('str_original equals str_decoded =', str_original == str_decoded)

出力:

<class 'bytes'>
<class 'str'>
Encoded bytes = b'Hello'
Decoded String = Hello
str_original equals str_decoded = True

上記の例はエンコードの使用方法をはっきり示していません。ユーザーからの入力を受け取ってそれをエンコードする別の例を見てみましょう。ユーザーが入力した文字列にはいくつかの特殊文字が含まれています。

str_original = input('Please enter string data:\n')

bytes_encoded = str_original.encode()

str_decoded = bytes_encoded.decode()

print('Encoded bytes =', bytes_encoded)
print('Decoded String =', str_decoded)
print('str_original equals str_decoded =', str_original == str_decoded)
python string encode decode
Please enter string data:
aåb∫cçd∂e´´´ƒg©1¡
Encoded bytes = b'a\xc3\xa5b\xe2\x88\xabc\xc3\xa7d\xe2\x88\x82e\xc2\xb4\xc2\xb4\xc2\xb4\xc6\x92g\xc2\xa91\xc2\xa1'
Decoded String = aåb∫cçd∂e´´´ƒg©1¡
str_original equals str_decoded = True

私たちのGitHubリポジトリから、完全なPythonスクリプトとさらにPythonの例をチェックアウトすることができます。

参照: str.encode()のAPIドキュメント、bytes.decode()のAPIドキュメント

コメントを残す 0

Your email address will not be published. Required fields are marked *