RhythmInk
RhythmInk

Reputation: 553

What is the difference between print('text' +str(variable)) and print('stuff', variable) in python?

When writing print statements in python is it better practice to write

print('some text', variable, variable, expression)

or

print('some text' + str(variable) ...)

How is print handling these differently?

Upvotes: 1

Views: 309

Answers (3)

Vikram Palakurthi
Vikram Palakurthi

Reputation: 2506

I am not sure about Python, but as a basic difference would be related to the performance.

print('some text', variable, variable, expression) - This is called Parameterized which improves performance.

print('some text' + str(variable) ...) - incurs the cost of constructing the message parameter, i.e. converting the type to a String

Upvotes: 1

Kirk Strauser
Kirk Strauser

Reputation: 30957

In general,

print('some text', variable, variable, expression)

will be more efficient than

print('some text' + str(variable) ...)

which constructs a new string object, displays it, then immediately discards it. Unless the list of arguments is long and resulting string is huge, though, I doubt you'll ever notice the time difference. I think it's more important that the first is more idiomatic than the second.

Upvotes: 1

R Nar
R Nar

Reputation: 5515

your main difference is if you were to "parameterize" the print function (as Vikram so eloquently said), print has a default sep parameter that separates your parameters with whatever sep may be (defaulted to a ' '). without splitting your variables into parameters and just concatenating them into one string, there will be no spaces. ie:

>>> print(1,2)
1 2
>>> print(str(1)+str(2))
12

I think another thing you are wondering is the calling of str. Simply put, print calls str(parameter) on your parameters regardless so, in that respect, there really is no difference.

In conclusion, the string that is outputted by print acts almost identical to:

sep.join(parameters) #where sep is defaulted to ' '

Upvotes: 1

Related Questions