1

Is there an easy way in python to add a permanent character (or string) to several prints ?

Example:

add_string('Hello ')
print('World')
print('You')

would output

Hello World
Hello You

Is there a way to do it without changing the following part of the code:

print('World')
print('You')
PatriceG
  • 3,851
  • 5
  • 28
  • 43
  • 1
    Related: [overload print python](http://stackoverflow.com/questions/550470/overload-print-python). – alecxe Nov 06 '14 at 16:41

4 Answers4

1

You could have your add_string function overwrite the builtin print function:

from __future__ import print_function  # for python 2.x

def add_string(prefix):
    def print_with_prefix(*args, **kwargs):
        if prefix:
            args = (prefix,) + args
        __builtins__.print(*args, **kwargs)
    global print
    print = print_with_prefix

You can set or unset the prefix while preserving any other arguments passed to print.

print("foo")                                  # prints 'foo'
add_string(">>>")
print("bar")                                  # prints '>>> bar'
print("bar", "42", sep=' + ', end="###\n")    # prints '>>> + bar + 42###'
add_string(None)
print("blub")                                 # prints 'blub'

If you are using the print statement (i.e. print "foo" instead of print("foo")) then you have to redefine sys.stdout with a custom writer:

import sys
stdout = sys.stdout
def add_string(prefix):
    class MyPrint:
        def write(self, text):
            stdout.write((prefix + text) if text.strip() else text)
    sys.stdout = MyPrint() if prefix else stdout
tobias_k
  • 81,265
  • 12
  • 120
  • 179
  • Thanks for your answer. However, I've got numerous print with python 2.x syntax (print 'haha'), and they produce errors with python 3. – PatriceG Nov 07 '14 at 10:27
  • In this case you will have to replace `sys.stdout` with a custom writer. – tobias_k Nov 07 '14 at 10:54
0

Because you want to add it to several, but not all, it might be best to use a self-made function that adds something, so you can just call that function for the cases where you want to add it, and don't in the cases you don't want to add it

def custom_print(text):
    print('Hello ' + text)

custom_print('World') # output: Hello World
Tim
  • 41,901
  • 18
  • 127
  • 145
0

try like this:

def my_print(custom="Hello",my):
    print(custom + ' ' + my)
my_print(my='world')
my_print(my="you")
my_print(custom="Hey",'you')

output:

Hello world
Hello you
Hey you

you can use custom key argument of form kwarg = Value
for more check here https://docs.python.org/3/tutorial/controlflow.html#keyword-arguments

Hackaholic
  • 19,069
  • 5
  • 54
  • 72
0
from __future__ import print_function # needed for python 2.7


def print(*args, **kwargs):
    return __builtins__.print("Hello",*args, **kwargs)

print('World')
Hello World
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321