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!
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.
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.
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.
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.
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
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