Jim Newton
Jim Newton

Reputation: 652

How to print to a string in Python

Lisp type languages usually provide an abstraction which allows you to open a string as a file, and then print to it using any function which can normally print to a file. When you close the string you can recuperate the string that was printed.

Does something like this exist for python?

It probably would like something like this:

f = open_string_as_output()
f.write("hello")
if some_condition:
   f.write(" ")
g(f) # allow g to write to the sting if desired
f.close()
str = f.get_string()

Upvotes: 1

Views: 2392

Answers (3)

quickbug
quickbug

Reputation: 4848

the io module allows exactly that: use the versatility of the print() function with the flux redirected to a string.

from io import StringIO
output = StringIO()
print("Hello World!", file=output)
print(f"I have written so far this to my string: {output.getvalue()}", file=output)

result = output.getvalue()
print(result)

outputs:

Hello World!
I have written so far this to my string: Hello World!

You cannot overuse this technique. See this example:

from io import StringIO
garbage = StringIO()

def foo(stuff, out_flux=None):
    ''' A function that prints stuff but you need to mute from time to time. '''
    result = stuff
    print(result, file=out_flux)

# normal use
foo(10) # prints 10

# muted use
foo(10, out_flux=garbage) # prints nothing
print(garbage.getvalue()) # prints whatever was collected so far

Upvotes: 2

Toothpick Anemone
Toothpick Anemone

Reputation: 4644

There is somthing called a string stream which might help you.

import io # the library for input and output 
       
words = ["PEPPERS", "SWEET", "BELL", "AMPIUS", "PKT" "$2.00"] 

str_strm = io.StringIO()
   
# `sep` is `separator`    
# `end` is `end of line`

print(*iter(words), sep="...", end="\r\n", file=str_strm)

final_result = str_strm.getvalue()

str_strm.close() # a close the string stream to avoid a memory leak 

However, there are simpler ways to print to a string.

def print2str(*args, sep=' ', end='\n') -> str:
    it = iter(str(arg) for arg in args) 
    result = sep.join(it) + end
    return result 

Upvotes: 1

Brian
Brian

Reputation: 7654

There is a class called StringIO, which does what you described.

import io
string_out = io.StringIO()
string_out.write('Foo')
if some_condition:
    string_out.write('Bar')
string_out.getvalue()  # Could be 'Foo' or 'FooBar'

Upvotes: 4

Related Questions