Transferred from: http://www.cnblogs.com/wushuaishuai/p/7686290.html
Describe
The encode () method encodes a string in the specified encoding format, and the default encoding is ' Utf-8 '.
Corresponding decoding method: Bytes decode () method.
Grammar
Encode () method syntax:
1
S.encode([encoding
=
‘utf-8‘
][,errors
=
‘strict‘
])
Parameters
- Encoding--optional parameter, the encoding to use, the default encoding is ' Utf-8 '.
- Errors--optional parameter, set different error handling scheme. The default is ' strict ', which means a unicodeerror is caused by a coding error. Other possible values are ' ignore ', ' replace ', ' xmlcharrefreplace ', ' backslashreplace ' and any value registered through Codecs.register_error ().
return value
The method returns the encoded string, which is a bytes object.
Example:
#!/usr/bin/env python
#-*-Coding:utf-8-*-
s = " Beginner's tutorial "
S_utf8 = S.encode("utf-8")
S_GBK = S.encode("gbk")
Print (s)
Print ("", S_utf8)
Print ("", S_GBK)
Print ("", S_utf8. Decode (' Utf-8 '))
Print ("", S_GBK. Decode (' GBK '))
Output:
Beginner's Tutorial
Utf-8 code: B ' \xe8\x8f\x9c\xe9\xb8\x9f\xe6\x95\x99\xe7\xa8\x8b '
GBK code: B ' \XB2\XCB\XC4\XF1\XBD\XCC\XB3\XCC '
Utf-8 decoding: Beginner's tutorial
GBK decoding: Beginner's tutorial
Note:
- STR uses the Decode method to decode it to a Unicode string type based on the encoding of STR.
- STR uses encode to convert a Unicode string type to a specific encoding based on a specific encoding
Python Encode () method (GO)