Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python bytes(some_string, 'UTF-8') and str(some_string, 'UTF-8')

I want to adapt a code written for python3 to python2.7 while doing so I am getting errors because of the this two

bytes(some_string, 'UTF-8') and str(some_string, 'UTF-8')

My Question:

Is following a correct way to adapt str(some_string, 'UTF-8')

a = str(some_string)

a = a.encode('UTF-8')

and how to adapt bytes(some_string, 'UTF-8') to python2.7 as bytes are introduced in python3.

like image 898
rahulk9 Avatar asked Dec 22 '16 08:12

rahulk9


1 Answers

Just some_string or str(some_string) will do in python2, since some_string is already an ascii string, and both of those actions convert it to type str. In python 3 the str type is the same as the unicode type in python 2.

Please read this answer, I think it answers your questions nicely.

In Python 2, str and bytes are the same type:

bytes is str True In Python 3, the str type is Python 2's unicode type, which is the default encoding of all strings.

In other words, bytes(some_string, 'UTF-8') in python 2 is just str(some_string), because str is a byte string.

like image 136
Roman Avatar answered Oct 27 '22 02:10

Roman