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.

Community
  • 1
  • 1
rahulk9
  • 795
  • 3
  • 10
  • 20
  • in python 2 normal string is bytes, and `string.decode()` convert it into unicode. In python 3 normal string is unicode. – furas Dec 22 '16 at 08:37
  • I cant't test it but `str(some_string, 'utf-8')` can be `some_string.decode('utf-8')` and `bytes(some_string, 'utf-8')` can be `some_string.encode('utf-8')` – furas Dec 22 '16 at 08:40

1 Answers1

5

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.

Community
  • 1
  • 1
Roman
  • 8,826
  • 10
  • 63
  • 103