Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is StringIO used, as opposed to joining a list of strings?

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 
like image 859
simha Avatar asked Jan 19 '11 09:01

simha


People also ask

What is StringIO used for?

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.

How do you define StringIO?

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.

What is BytesIO Python?

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.


1 Answers

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() 
like image 73
TryPyPy Avatar answered Sep 24 '22 20:09

TryPyPy