PatriceG
PatriceG

Reputation: 4063

Add permanent character to following prints

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')

Upvotes: 1

Views: 138

Answers (4)

tobias_k
tobias_k

Reputation: 82899

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

Upvotes: 1

Hackaholic
Hackaholic

Reputation: 19733

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

Upvotes: 0

Padraic Cunningham
Padraic Cunningham

Reputation: 180411

from __future__ import print_function # needed for python 2.7


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

print('World')
Hello World

Upvotes: 0

Tim
Tim

Reputation: 43314

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

Upvotes: 0

Related Questions