10

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.

2
  • in python 2 normal string is bytes, and string.decode() convert it into unicode. In python 3 normal string is unicode. Commented Dec 22, 2016 at 8: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') Commented Dec 22, 2016 at 8:40

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.