Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between io.StringIO and a string variable in python

Tags:

python-3.x

I am new to python.

Can anybody explain what's the difference between a string variable and io.StringIO . In both we can save character.

e.g

String variable

k= 'RAVI'

io.stringIO

string_out = io.StringIO()
string_out.write('A sample string which we have to send to server as string data.')
string_out.getvalue()

If we print k or string_out.getvalue() both will print the text

print(k)
print(string_out.getvalue())
like image 978
Kandan Siva Avatar asked Aug 01 '18 06:08

Kandan Siva


2 Answers

They are similar because both str and StringIO represent strings, they just do it in different ways:

  • str: Immutable
  • StringIO: Mutable, file-like interface, which stores strs

A text-mode file handle (as produced by open("somefile.txt")) is also very similar to StringIO (both are "Text I/O"), with the latter allowing you to avoid using an actual file for file-like operations.

like image 180
L3viathan Avatar answered Oct 29 '22 09:10

L3viathan


you can use io.StringIO() to simulate files, since python is dynamic with variable types usually if you have something that accepts a file object you can also use io.StringIO() with it, meaning you can have a "file" in memory that you can control the contents of without actually writing any temporary files to disk

like image 2
AntiMatterDynamite Avatar answered Oct 29 '22 08:10

AntiMatterDynamite