Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

better way to pass data to print in python

Tags:

python

I was going through http://web2py.com/book/default/chapter/02 and found this:

>>> print 'number is ' + str(3)
number is 3
>>> print 'number is %s' % (3)
number is 3
>>> print 'number is %(number)s' % dict(number=3)
number is 3

It has been given that The last notation is more explicit and less error prone, and is to be preferred.

I am wondering what is the advantage of using the last notation.. will it not have a performance overhead?

like image 679
Shiv Deepak Avatar asked Dec 29 '25 11:12

Shiv Deepak


1 Answers

>>> print 'number is ' + str(3)
number is 3

This is definitely the worst solution and might cause you problems if you do the beginner mistake "Value of obj: " + obj where obj is not a string or unicode object. For many concatenations, it's not readable at all - it's similar to something like echo "<p>Hello ".$username."!</p>"; in PHP (this can get arbitrarily ugly).


print 'number is %s' % (3) number is 3

Now that is much better. Instead of a hard-to-read concatenation, you see the output format immediately. Coming back to the beginner mistake of outputting values, you can do print "Value of obj: %r" % obj, for example. I personally prefer this in most cases. But note that you cannot use it in gettext-translated strings if you have multiple format specifiers because the order might change in other languages.

As you forgot to mention it here, you can also use the new string formatting method which is similar:

>>> "number is {0}".format(3)
'number is 3'


Next, dict lookup:
>>> print 'number is %(number)s' % dict(number=3)
number is 3

As said before, gettext-translated strings might change the order of positional format specifiers, so this option is the best when working with translations. The performance drop should be negligible - if your program is not all about formatting strings.

As with the positional formatting, you can also do it in the new style:

>>> "number is {number}".format(number=3)
'number is 3'


It's hard to tell which one to take. I recommend you to use positional arguments with the % notation for simple strings and dict lookup formatting for translated strings.
like image 64
AndiDog Avatar answered Jan 01 '26 02:01

AndiDog



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!