4

Is there a Python class that wraps the file interface (read, write etc.) around a string? I mean something like the stringstream classes in C++.

I was thinking of using it to redirect the output of print into a string, like this

sys.stdout = string_wrapper()
print "foo", "bar", "baz"
s = sys.stdout.to_string() #now s == "foo bar baz"

EDIT: This is a duplicate of How do I wrap a string in a file in Python?

Community
  • 1
  • 1
CAdaker
  • 14,385
  • 3
  • 30
  • 32

2 Answers2

12

Yes, there is StringIO:

import StringIO
import sys


sys.stdout = StringIO.StringIO()
print "foo", "bar", "baz"
s = sys.stdout.getvalue()
Peter Hoffmann
  • 56,376
  • 15
  • 76
  • 59
2

For better performance, note that you can also use cStringIO. But also note that this isn't very portable to python 3.

Jason Baker
  • 192,085
  • 135
  • 376
  • 510