Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom print function that wraps print()

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.

like image 808
user2316370 Avatar asked Oct 09 '14 19:10

user2316370


2 Answers

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')
like image 143
Jaimin Patel Avatar answered Sep 19 '22 13:09

Jaimin Patel


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)
like image 41
Padraic Cunningham Avatar answered Sep 18 '22 13:09

Padraic Cunningham