# Python CodeRecipe|encode()の使い方
❮ Home ❮ String Methods
# encode()の例1
txt = "My name is Ståle"
x = txt.encode()
print()
# encode()の定義及び使い方
encode()関数は文字列をエンコードします。 指定したエンコーディングを使用します。エンコード方式が指定されていない場合は、UTF-8が使用されます。
# encode()の構文
string.encode(encoding=encoding, errors=errors)
# encode()の引数
encoding オプション. A String specifying the encoding to use. Default is UTF-8
errors:オプション. A String specifying the error method. Legal values are: 'backslashreplace' - uses a backslash instead of the character that could not be encoded 'ignore'- ignores the characters that cannot be encoded 'namereplace'- replaces the character with a text explaining the character 'strict'- Default, raises an error on failure 'replace'- replaces the character with a questionmark 'xmlcharrefreplace'- replaces the character with an xml character
# Example
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")
print(txt.encode(encoding="ascii",errors="strict")
❮ Home ❮ String Methods