character encoding conversion

Peter Otten __peter__ at web.de
Mon Dec 13 10:09:32 CET 2004


Steven Bethard wrote:

> Christian Ergh wrote:
>> flag = true
>> for char in data:
>>     if 127 < ord(char) < 128:
>>         flag = false
>> if flag:
>>     try:
>>         data = data.encode('latin-1')
>>     except:
>>         pass
> 
> A little OT, but (assuming I got your indentation right[1]) this kind of
> loop is exactly what the else clause of a for-loop is for:
> 
> for char in data:
>      if 127 < ord(char) < 128:
>          break
> else:
>      try:
>          data = data.encode('latin-1')
>      except:
>          pass
> 
> Only saves you one line of code, but you don't have to keep track of a
> 'flag' variable.  Generally, I find that when I want to set a 'flag'
> variable, I can usually do it with a for/else instead.
> 
> Steve
> 
> [1] Messed up indentation happens in a lot of clients if you have tabs
> in your code.  If you can replace tabs with spaces before posting, this
> usually solves the problem.

Even more off-topic:

>>> for char in data:
...     if 127 < ord(char) < 128:
...             break
...
>>> print char
127.5

:-)

Peter




More information about the Python-list mailing list