character encoding conversion
Steven Bethard
steven.bethard at gmail.com
Mon Dec 13 03:58:15 EST 2004
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.
More information about the Python-list
mailing list