[python-nl] found a difference in result of print function in python2.6 versus python3 - bug or feature ?

Konrad Delong konryd at gmail.com
Wed Jan 19 10:24:27 CET 2011


This is expected, and has to do with Python's migration to unicode as
the default string type for the versions 3 and newer.

Roughly: strings in pre-3 Pythons are series of bytes, in order for
them to have meaning when encoding non-ascii characters you need to be
aware of their encoding (iso-8859-1, iso-8859-2 etc.). Here enters
unicode type - it is a series of unicode characters (a huge table -
much more than 256 values).

Now, the default string type in Python 3 is more or less what unicode
was in Python 2. This seems great, but when dealing with series of
bytes (without knowledge about their encoding), we are stuck. For
series of bytes, Python 3 uses the bytes type, which is roughly what
str in old Pythons was. One of the differences, however is the way
they are printed: the additional "b" prefix means we are not aware of
encoding of this series of bytes.

You can find a more thorough explanation here (I encourage you to read
the whole article, though):
    http://diveintopython3.org/strings.html#byte-arrays


cheers,
Konrad

On 18 January 2011 10:43, rick at intervisit.com <rick at intervisit.com> wrote:
> Hello,
>
> Being interested in python as a replacement environment for my existing
> codebase of Bash scripts, I stumbled across the following 'bug or feature':
>
> Reading data from a pipe in python2.6.4 yields exactly what I expect, while
> using python3.1.2, the output is enclosed with some b'  and '.
>
> I have been testing the following script:
> -------------
> import subprocess, sys
>
> ls = subprocess.Popen(['ls', '-l', '/etc/motd'], stdout=subprocess.PIPE,)
>
> end_of_pipe = ls.stdout
>
> print('Result:')
>
> for line in end_of_pipe:
>    print(line.strip())
> -------------
>
> Result from invoking with python2 and python3 are respectively:
>
> Result:
> -rw-rw---- 1 root root 25 Jan 18 10:25 /etc/motd
>
> and:
>
> Result:
> b'-rw-rw---- 1 root root 25 Jan 18 10:25 /etc/motd'
>
>
>
> Who is able to explain this to me ?
> Thanks in advance. R.
> _______________________________________________
> Python-nl mailing list
> Python-nl at python.org
> http://mail.python.org/mailman/listinfo/python-nl
>


More information about the Python-nl mailing list