print attitude
Andy Jewell
andy at wild-flower.co.uk
Fri Jul 4 18:39:26 EDT 2003
On Friday 04 Jul 2003 10:49 pm, Batista, Facundo wrote:
> One detail I found, don't now if it's ok:
>
> Python 2.1.1 (#4, Mar 8 2002, 12:32:24)
> [GCC 2.95.3 20010315 (release)] on sunos5
>
> >>> a = 'ñ'
> >>> a
>
> '\xf1'
>
> >>> print a
>
> ñ
>
> >>> l = ['ñ']
> >>> l
>
> ['\xf1']
>
> >>> print l
>
> ['\xf1']
>
>
> Is this OK?
>
> Why this different behaviour?
>
> Thank you!
>
> . Facundo
Facundo,
Short answer:
'ñ' is not in 7-bit ASCII, so python 'escapes' it, to it's hex value, when
evaluating it. ['ñ'] is a list, containing 1 string, and when displaying
lists (and other containers), python displays the escaped contents, as this
is the only way that 'makes sense'.
Long answer:
Remember, everything in Python is an Object, so...
>>> a=1 # and 'int' object, with the name 'a'
When you use print, it calls the __str__ method of the object you are
printing, which returns the 'string representation' of the object's data:
>>> print a
1
>>> print str(1)
1
When you just 'evaluate' the expression on the python command-line, the
__repr__ method of the object is called, which returns a 'quoted' string,
that can be used to re-create the object with the same value. For some types
(integers and floats), str(n) == repr(n) - their string representation is the
same as their quoted representation. For other types (strings for instance),
str(s) != repr(s)
>>> a
1
>>> repr(a)
1
>>> s="hello"
>>> print s
hello
>>> print str(s)
hello>>> ord("ñ")
UnicodeError: ASCII encoding error: ordinal not in range(128)
>>> print repr(s)
'hello'
If the object is a 'container' object - a list, tuple or dict, for example,
their __str__ method returns the same as their __repr__ function: a string
which can be used to recreate the object. So when you ask python to print
it, what you see is it's 'quoted' representation. How else would you print a
list? a dict? It only makes sense to print the 'quoted' version in these
cases.>>> ord("ñ")
UnicodeError: ASCII encoding error: ordinal not in range(128)
Ok - that covers a the mechanics, but what about your 'ñ'? Well, that's not a
standard 7-bit ASCII character. Python is '7-bit ASCII clean' - which means
it ONLY uses characters 0-127 in program code. Programs can manipulate any
character code, but you can't write them in python /directly/:
(on my box i get this):
>>> ord("ñ")
UnicodeError: ASCII encoding error: ordinal not in range(128)
I notice you're using an older version of Python than me (2.1.1) - I believe
this *does* allow coded over 127 (but I'm not sure of the rules).
Right, when you ask python to print a list like ['ñ'], it simply prints the
'quoted' data in it data structure. As 'ñ' > chr(127), it 'escapes' it to
it's hex value '\xf1'.
If I've got any of that wrong/inaccurate, I'm sure one of the Kindred will
correct me :-)
hope that helps
-andyj
More information about the Python-list
mailing list