You can use the functon truncate()
. It doesn't delete the stream but resizing it, so giving it a value of 0 should get rid of all the bytes in the stream. You will also need to use seek()
to change the position of the stream. Same as truncate(), giving it a value of 0 should offset the position to the start of the stream. Good luck!
import io
string_out = io.StringIO()
string_out.write("hello")
print(string_out.getvalue())
string_out.seek(0)
string_out.truncate(0)
string_out.write("new Hello")
print(string_out.getvalue())
Update: What's the difference between truncate(0) and truncate()?
truncate() uses the current default position, while truncate(0) uses the start position. Because you already specified seek(0) before truncate(0), the position is swetched to the start of the sentence before truncating. The below examples should clear it up for you.
- Using
seek(10)
and truncate()
:

- Using
seek(0)
and truncate()
:
