I think that this could be rewritten to only call `len()` three times in this whole function.  Since this is writing output it is not performance critical but I think would be a good thing to do anyways.  This won't block this PR.