Why are you writing to a StringIO object and reading from it, rather than just creating a string and returning it?