Using StringIO as string buffer is slower than using list as buffer.
When is StringIO used?
from io import StringIO def meth1(string): a = [] for i in range(100): a.append(string) return ''.join(a) def meth2(string): a = StringIO() for i in range(100): a.write(string) return a.getvalue() if __name__ == '__main__': from timeit import Timer string = "This is test string" print(Timer("meth1(string)", "from __main__ import meth1, string").timeit()) print(Timer("meth2(string)", "from __main__ import meth2, string").timeit())
Results:
16.7872819901 18.7160351276
The StringIO module is an in-memory file-like object. This object can be used as input or output to the most function that would expect a standard file object. When the StringIO object is created it is initialized by passing a string to the constructor. If no string is passed the StringIO will start empty.
Strings are defined as an array of characters. The difference between a character array and a string is the string is terminated with a special character '\0'. Declaration of strings: Declaring a string is as simple as declaring a one-dimensional array. Below is the basic syntax for declaring a string.
StringIO and BytesIO are methods that manipulate string and bytes data in memory. StringIO is used for string data and BytesIO is used for binary data. This classes create file like object that operate on string data. The StringIO and BytesIO classes are most useful in scenarios where you need to mimic a normal file.
The main advantage of StringIO is that it can be used where a file was expected. So you can do for example (for Python 2):
import sys import StringIO out = StringIO.StringIO() sys.stdout = out print "hi, I'm going out" sys.stdout = sys.__stdout__ print out.getvalue()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With