python字串-編碼(encode)
阿新 • • 發佈:2022-04-05
encode方法用於使用指定的編碼格式對字串進行編碼。
語法
encode(encoding='utf-8', errors='strict')
引數
- encoding: 編碼格式,預設為‘utf-8’。
- errors: 不同錯誤的處理方案,預設值為strict。
- strict:遇到非法字元就丟擲異常。
- ignore:忽略非法字元。
- replace:用“?”替換非法字元。
- xmlcharrefreplace:使用 xml 的字元引用。
返回值
- 編碼後的字串。
示例
str = '我愛我的爸媽' print('預設為utf-8編碼:', str.encode()) print('utf-8明示編碼:', str.encode('UTF-8')) print('GBK編碼:', str.encode('GBK', 'strict')) try: print('BIG5編碼:', str.encode('BIG5', 'strict')) except UnicodeError as err: print('出錯了:', err) print('BIG5編碼,igonre引數忽略非法字元:', str.encode('BIG5', 'ignore'))
預設為utf-8編碼: b'\xe6\x88\x91\xe7\x88\xb1\xe6\x88\x91\xe7\x9a\x84\xe7\x88\xb8\xe5\xa6\x88' utf-8明示編碼: b'\xe6\x88\x91\xe7\x88\xb1\xe6\x88\x91\xe7\x9a\x84\xe7\x88\xb8\xe5\xa6\x88' GBK編碼: b'\xce\xd2\xb0\xae\xce\xd2\xb5\xc4\xb0\xd6\xc2\xe8' 出錯了: 'big5' codec can't encode character '\u7231' in position 1: illegal multibyte sequence BIG5編碼,igonre引數忽略非法字元: b'\xa7\xda\xa7\xda\xaa\xba\xaa\xa8'
help()
Help on built-in function encode: encode(encoding='utf-8', errors='strict') method of builtins.str instance Encode the string using the codec registered for encoding. encoding The encoding in which to encode the string. errors The error handling scheme to use for encoding errors. The default is 'strict' meaning that encoding errors raise a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and 'xmlcharrefreplace' as well as any other name registered with codecs.register_error that can handle UnicodeEncodeErrors.