Steven D'Aprano wrote: > You should consider factoring out some repeated code > into functions. E.g.: > > # warning: untested!!! > def replace_all(s, old, new): > """Replaces all instances of substring old with > substring new.""" > if old == new: > # make no changes > return s > elif old in new: > raise ValueError("old substring can't be " > "part of the replacement substring.") > while old in s: > s = s.replace(old, new) > return s > > Now you can call it in your loop: > > > for path, subdirs, files in os.walk(dir, topdown=True): > > oldname = path > > newname = oldname.translate(chars) > > newname = string.lower(newname) > > > while string.count(newname, "__") > 0: > > newname = string.replace(newname,"__","_") > > while string.count(newname, "..") > 0: > > newname = string.replace(newname,"..",".") > > becomes: > > newname = replace_all(newname, "__", "_") > newname = replace_all(newname, "..", ".")
or you can use a more well-suited function: # replace runs of _ and . with a single character newname = re.sub("_+", "_", newname) newname = re.sub("\.+", ".", newname) or, slightly more obscure: newname = re.sub("([_.])\\1+", "\\1", newname) </F> -- http://mail.python.org/mailman/listinfo/python-list