Pushpak Yadav
Pushpak Yadav

Reputation: 21

Behavior of print() function in python

Consider the following code:


    name = "Lelouch"
    print("Hello", name)  #1
    print("Hello " + name) #2
    #end of code

Here I would like to know the difference between 1 and 2. Is it just a different way of making strings from the different objects and printing them via the output stream or is it some other major difference?

Upvotes: 0

Views: 250

Answers (2)

mozway
mozway

Reputation: 260300

The parameter expansion enables you to quickly print things separated by a common separator,:

print(*['a', 'b', 'c'], sep='-')
# a-b-c

I think this way is quite nice for beginners as it enables to mix types and not worry about concatenation:

name = 'ABC'
N = 123
print(name, 'has value', N)
# ABC has value 123

However it is much slower to parse parameters, than to prepare a single string to print.

Let's start with 10k numbers (as strings):

l = list(map(str, range(10000)))

and print them:

%%time
print(*l, sep=',')
# takes ~1s

or, prepare a single string with join:

%%time
print(','.join(l))
# takes ~2ms

Upvotes: 0

Grismar
Grismar

Reputation: 31319

The first print statement receives two arguments and prints one after the other, separating them with as a space, which is the default behaviour for print().

The second statement constructs a new string out of the two given and then prints it, no spaces needed as there is only one argument.

The main difference is that the first doesn't bother to construct a new string before printing and it would work with a name of any data type that has a string form (i.e. implements __str__). The second will only work if name is also a string (or at least implements being added to a string).

Typically, the first would be preferred, if all you need is for these values to be printed with a space between them.

If you want to do some more formatting, consider using an f-string, instead of adding the strings:

print(f'Hello\t{name}')  # prints with a tab in between, instead of space

Upvotes: 2

Related Questions