Performing String and Bytes Data Conversion in Python3.x

In Python 3.5 String and Bytes are not same as in Python2.7, the manual conversion between them need to done using and  encode<==> decode method.

String===>(encode)==>Byte===>(decode)==>String

 

String Encode:

encode(…) method of builtins.str instance
S.encode(encoding=’utf-8′, errors=’strict’) -> bytes

Bytes Decode:

decode(…) method of builtins.bytes instance

B.decode(encoding=’utf-8′, errors=’strict’) -> str

 

While doing Python 2.7 to Python 3.5 migration the most common issue is related to Text(String and Bytes) data type, One of such common issue is:

TypeError: a bytes-like object is required, not ‘str’

Error occurs due to the type mismatch of bytes and string.

For solving this error encode the string data to bytes format by calling string_data.encode() .

 

Python 3.x the unicode type has been renamed as str and the older str type has been replaced bybytes.

See the below example  (in Python 2.x)

#Bytes and String data is same.

bytes==str  #True

help(bytes) #class str(basestring)

help(str) #class str(basestring)


#String and Unicode data is different.

str==unicode # False
help(str) #class str(basestring)

help(unicode) #class unicode(basestring)

 

The same code in Python3.x

#Bytes and String data is different.

bytes==str  #False

help(bytes) #class bytes(object)
help(str) #class str(object)

#Unicode  data type not exists.

unicode#NameError: name 'unicode' is not defined

 

That’s all for today. I hope this blog will help you. I’d be very grateful if you’d write your opinions, comments and suggestions to keep the page updated and interesting.

 

. . .

Ask a Feature