Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python3 encode() Method

Python3 encode() Method

Python3 Strings Python3 Strings


Description

The encode() method encodes a string using the specified encoding. The errors parameter can specify different error handling schemes.

Syntax

Syntax of the encode() method:


str.encode(encoding='UTF-8',errors='strict')

Parameters

Return Value

This method returns the encoded string as a bytes object.

Example

The following example demonstrates the encode() method:

Example (Python 3.0+)

#!/usr/bin/python3

str

=

"

Runoob Tutorial

"

;

str_utf8

=

str

.

encode

(

"

UTF-8

"

)

str_gbk

=

str

.

encode

(

"

GBK

"

)

print

(

str

)

print

(

"

UTF-8 encoding:

"

,

str_utf8

)

print

(

"

GBK encoding:

"

,

str_gbk

)

print

(

"

UTF-8 decoding:

"

,

str_utf8

.

decode

(

'

UTF-8

'

,

'

strict

'

)

)

print

(

"

GBK decoding:

"

,

str_gbk

.

decode

(

'

GBK

'

,

'

strict

'

)

)

The output of the above example is:


Runoob Tutorial
UTF-8 编码: b'\xe8\x8f\x9c\xe9\xb8\x9f\xe6\x95\x99\xe7\xa8\x8b'
GBK 编码: b'\xb2\xcb\xc4\xf1\xbd\xcc\xb3\xcc'
UTF-8 解码: Runoob Tutorial
GBK 解码: Runoob Tutorial

Python3 Strings Python3 Strings