character encoding conversion

Christian Ergh christian.ergh at gmail.com
Mon Dec 13 04:32:12 EST 2004


Peter Otten wrote:
> 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
> 
Well yes, that happens when doing a quick hack and not reviewing it, 128 
has to be 160 of course...



More information about the Python-list mailing list