variable assignment within a loop

Alex Martelli aleax at aleax.it
Tue Nov 4 12:09:31 EST 2003


Michael Surette wrote:

> On Mon, 03 Nov 2003 15:37:28 -0500, hokieghal99 wrote:
> 
>> I have this for loop in a program that I'm writing:
>> 
>>          for bad_dir_char in bad_dir_chars:
>>              newdir = dir.replace(bad_dir_char,'-')
   ...
>> I get a "local variable 'newdir' referenced before assignment" error.
> 
> This has nothing to do with where variables live.  What is happening is
> when bad_dir_chars is empty, newdir doesn't get assigned in your for loop.

Right -- and when bad_dir_chars has more than one character, all
but the last one are basically ignored (they ARE used to laboriously
compute many versions of newdir, but all versions except the last
one are thrown away).

Do, instead:

import string

transbad = string.maketrans(bad_dir_chars, '-'*len(bad_dir_chars))

newdir = dir.translate(transbad)


this no doubt has the effect you were looking for...


Alex





More information about the Python-list mailing list