i want to save print function output to my var without printing console. (sprintf function in C)
var = specific_print("hello", "my dear", "how are", "you", sep = " ", end = " ?", return_string = True, print_console = False)
print(var)
# output => hello my dear how are you ?
You can't - print function returns
None
In [5]: print(print(1))
1
None
Here is what print function can do
In [7]: print?
Docstring:
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.
Type: builtin_function_or_method
There is also no need to. If you want formatted output, you may use formatting options; if you want to concatenate strings with spaces -
' '.join([<list of strings>])
is your friend
@
volcano63,
Thanks.
i solved my problem with the following code
def myprint(*args, sep=" ", end="\n"):
return sep.join(args) + end
You could also redirect the output to a stringio object...
>>> import io
>>> text = io.StringIO()
>>> print("just some stuff", file=text)
>>> print("more things", file=text)
>>> text.seek(0)
0
>>> text.readlines()
['just some stuff\n', 'more things\n']
>>> text.getvalue()
'just some stuff\nmore things\n'
+1 for io.StringIO
Or you can rewrite the print function
print_bak = print
def print(*args, **kwargs):
return args
text = print([1,2,3,4])
print = print_bak
(May-08-2017, 09:49 PM)nilamo Wrote: [ -> ]You could also redirect the output to a stringio object...
(May-09-2017, 09:39 AM)wavic Wrote: [ -> ]Or you can rewrite the print function
With all due respect, those are more of hacks...
Though for concatenating many small strings into a bigger one
io.StringIO
is a good option (especially if performance is an issue ..., especially for OP

)