[Tutor] encoding question

Alex Kleider akleider at sonic.net
Sun Jan 5 01:15:30 CET 2014


On 2014-01-04 15:52, Steven D'Aprano wrote:

> Oh great. An exception was raised. What sort of exception? What error
> message did it have? Why did it happen? Nobody knows, because you throw
> it away.
> 
> Never, never, never do this. If you don't understand an exception, you
> have no business covering it up and hiding that it took place. Never 
> use
> a bare try...except, always catch the *smallest* number of specific
> exception types that make sense. Better is to avoid catching exceptions
> at all: an exception (usually) means something has gone wrong. You
> should aim to fix the problem *before* it blows up, not after.
> 
> I'm reminded of a quote:
> 
> "I find it amusing when novice programmers believe their main job is
> preventing programs from crashing. ... More experienced programmers
> realize that correct code is great, code that crashes could use
> improvement, but incorrect code that doesn't crash is a horrible
> nightmare." -- Chris Smith
> 
> Your code is incorrect, it does the wrong thing, but it doesn't crash,
> it just covers up the fact that an exception occured.
> 
> 
>> The output I get on an Ubuntu 12.4LTS system is as follows:
>> alex at x301:~/Python/Parse$ ./IP_info.py3
>> Exception raised.
>>     IP address is 201.234.178.62:
>>         Country: COLOMBIA (CO);  City: b'Bogot\xe1'.
>>         Lat/Long: 10.4/-75.2833
>> 
>> 
>> I would have thought that utf-8 could handle the 'a-acute'.
> 
> Of course it can:
> 
> py> 'Bogotá'.encode('utf-8')

I'm interested in knowing how you were able to enter the above line 
(assuming you have a key board similar to mine.)


> b'Bogot\xc3\xa1'
> 
> py> b'Bogot\xc3\xa1'.decode('utf-8')
> 'Bogotá'
> 
> 
> But you don't have UTF-8. You have something else, and trying to decode
> it using UTF-8 fails.
> 
> py> b'Bogot\xe1'.decode('utf-8')
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe1 in position 5:
> unexpected end of data
> 
> 
> More to follow...


I very much agree with your remarks.
In a pathetic attempt at self defence I just want to mention that what I 
presented wasn't what I thought was a solution.
Rather it was an attempt to figure out what the problem was as a 
preliminary step to fixing it.
With help from you and others, I was successful in doing this.
And for that help, I thank all list participants very much.



More information about the Tutor mailing list