Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python3 print to string

Using Python 3, I have a console application that I am porting to a GUI. The code has a bunch of print statements, something like this:

print(f1(), f2(), f3(), sep=getsep(), end=getend())

I would like to convert these calls into something like:

GuiPrintLine(f1(), f2(), f3(), sep=getsep(), end=getend())

where each line is eventually rendered using some (undefined) GUI framework.

This is easy to do if I can convert the arguments to print into to the string that print would normally produce without the side-effect of actually printing to sysout. In other words, I need a function like this:

s = print_to_string(*args, **kwargs)

How do I format a set of parameters to print(...) into a single string that produces the same output as print() would produce?

I realize I could emulate print by concatenating all the args with sep and ends, but I would prefer to use a built-in solution if there is one.

Using print and redirecting sysout is not attractive since it requires modifying the global state of the app and sysout might be used for other diagnostics at the same time.

It seems like this should be trivial in Python, so maybe I'm just missing something obvious.

Thanks for any help!

like image 692
Brad Avatar asked Oct 03 '16 01:10

Brad


People also ask

How do you print a string in Python?

The general syntax for creating an f-string looks like this: print(f"I want this text printed to the console!") #output #I want this text printed to the console! You first include the character f before the opening and closing quotation marks, inside the print() function.

Is print () supported in Python 3?

No, you cannot. The print statement is gone in Python 3; the compiler doesn't support it anymore. This will remove support for the print statement in Python 2 just like it is gone in Python 3, and you can use the print() function that ships with Python 2.

What does %S and %D do in Python?

They are used for formatting strings. %s acts a placeholder for a string while %d acts as a placeholder for a number. Their associated values are passed in via a tuple using the % operator.

How do you use %s in Python 3?

The %s operator is put where the string is to be specified. The number of values you want to append to a string should be equivalent to the number specified in parentheses after the % operator at the end of the string value.


1 Answers

Found the answer via string io. With this I don't have to emulate Print's handling of sep/end or even check for existence.

import io

def print_to_string(*args, **kwargs):
    output = io.StringIO()
    print(*args, file=output, **kwargs)
    contents = output.getvalue()
    output.close()
    return contents
like image 96
Brad Avatar answered Oct 20 '22 10:10

Brad