Monday, August 25, 2014

Key differences between Python 2.7.x and Python 3.x

This article describe the main differences between Python 2 and 3.

From my perspective, this is the most important change of all:

Unicode

Python 2 has ASCII str() types, separate unicode(), but no byte type.
Now, in Python 3, we finally have Unicode (utf-8) strings, and 2 byte classes: byte and bytearrays.

Python 2

In [2]: print 'Python', python_version()
Python 2.7.6
In [3]: print type(unicode('this is like a python3 str type'))
<type 'unicode'>
In [4]: print type(b'byte type does not exist')
<type 'str'>
In [5]: print 'they are really' + b' the same'
they are really the same
In [7]: print type(bytearray(b'bytearray oddly does exist though'))
<type 'bytearray'>

Python 3

In [6]:
print('Python', python_version())
print('strings are now utf-8 \u03BCnico\u0394é!')
Python 3.4.1
strings are now utf-8 μnicoΔé!
In [8]:
print('Python', python_version(), end="")
print(' has', type(b' bytes for storing data'))
Python 3.4.1 has <class 'bytes'>
In [11]:
print('and Python', python_version(), end="")
print(' also has', type(bytearray(b'bytearrays')))
and Python 3.4.1 also has <class 'bytearray'>
In [13]:
'note that we cannot add a string' + b'bytes for data'
--------------------------------------------------------------------------- 
TypeError Traceback (most recent call last)
<ipython-input-13-d3e8942ccf81> in <module>()  
----> 1 'note that we cannot add a string' + b'bytes for data'

TypeError: Can't convert 'bytes' object to str implicitly
 
 
 
Full article: http://nbviewer.ipython.org/github/rasbt/python_reference/blob/master/tutorials/key_differences_between_python_2_and_3.ipynb 

No comments:

Post a Comment