python字符串-編碼(encode)


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.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM