[Tutor] ASCII Code

Walter Vannini walterv@jps.net
Mon, 28 May 2001 06:52:06 -0700


Hi Timothy,

It looks like you're asking "why does printing a list
differ from printing each element of a list?".

For example, define the following function and three lists.
 
def PrintList(list):
    print "[",
    for i in list:
        print i,
    print "]"
aList = [ 1, 2]
bList = [ 1/10.0, 1/5.0 ]
cList = [ chr(1), chr(2)]

I then get the following in Python 2.0
>>> print aList
[1, 2]
>>> PrintList(aList)
[ 1 2 ]
which is reasonably consistent print behaviour.

However
>>> print bList
[0.10000000000000001, 0.20000000000000001]
>>> PrintList(bList)
[ 0.1 0.2 ]
which is very different printing behaviour.

And finally, your example, print cList and PrintList(cList)
>>> print cList
['\001', '\002']
>>> PrintList(cList)
---unprintable in ascii mail---
results in very different printing behaviour.

>From these experiments, my guess is that when print is used on an object,
the builtin function str is used. When print is used on a list,
it looks like the str builtin function calls the repr builtin function
repeatedly.

So for example, "print bList" uses the strings repr(1/10.0)
and repr(1/5.0), while "PrintList(bList)" uses the strings
str(1/10.0) and str(1/5.0).

>>> repr(1/10.0)
'0.10000000000000001'
>>> str(1/10.0)
'0.1'

This would imply that the seemingly inconsistent behaviour
you observed is due to the different behaviour of str and repr.
I hope someone with more knowledge of the python internals
can confirm the above guess.

Walter.

Timothy M. Brauch wrote:
> 
> I'm just a little curious about something I find odd in Python.  Here
> are two scripts that do pretty much the same thing...
> 
> ---Script 1---
> chars=[]
> for num in range(0,256):
>     chars.append(chr(num))
> for item in chars:
>     print item
> ---End Script---
> 
> ---Script 2---
> for num in range(0,256):
>     print chr(num)
> ---End Script---
> 
> Both scripts have the same output.  But, if in the first script you look
> at chars, you don't see the same characters that are printed.  Instead,
> you see the normal 'keyboard' letters and then the (octal) code '\177',
> '200', etc. for all the special characters.  Obviously Python can
> display those other characters, it did when I printed them.
> ...