How can I wrap print()
so that I can add arbitrary strings to the beginning and end of the things that are passed as arguments to get printed?
def xprint(*args):
print("XXX", *args, "XXX")
xprint("hi", "yo", 4)
doesn't work.
Basically, I want my custom function xprint()
to work like print()
but add 'XXX'
to the beginning and end of every output.
You can do the same thing without changing print function name. Just add below code in your script.
xprint = print
def print(*args, **kwargs):
# do whatever you want to do
xprint('statement before print')
xprint(*args, **kwargs)
print(f'hello')
Will work for python 2 and 3 when there are no keyword arguments
def xprint(*args):
print( "XXX"+" ".join(map(str,args))+"XXX")
In [5]: xprint("hi", "yo", 4)
XXXhi yo 4XXX
For the python 3 print()
function (or when using print_function
from __future__
in python 2), keyword arguments may be present as well. To ensure these are passed use the form
def xprint(*args, **kwargs):
print( "XXX"+" ".join(map(str,args))+"XXX", **kwargs)
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