Python文字列encode()メソッド
例
UTF-8は文字列をエンコードします:
txt = "My name is Ståle"
x = txt.encode()
print(x)
定義と使用法
このencode()
メソッドは、指定されたエンコーディングを使用して文字列をエンコードします。エンコーディングが指定されていない場合は、UTF-8が使用されます。
構文
string.encode(encoding=encoding, errors=errors)
パラメータ値
Parameter | Description | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
encoding | Optional. A String specifying the encoding to use. Default is UTF-8 | ||||||||||||
errors | Optional. A String specifying the error method. Legal values are:
|
その他の例
例
これらの例では、ASCIIエンコードと、エンコードできない文字を使用して、さまざまなエラーの結果を示しています。
txt = "My name is Ståle"
print(txt.encode(encoding="ascii",errors="backslashreplace"))
print(txt.encode(encoding="ascii",errors="ignore"))
print(txt.encode(encoding="ascii",errors="namereplace"))
print(txt.encode(encoding="ascii",errors="replace"))
print(txt.encode(encoding="ascii",errors="xmlcharrefreplace"))