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?
This is definitely the worst solution and might cause you problems if you do the beginner mistake
"Value of obj: " + objwhereobjis not a string or unicode object. For many concatenations, it’s not readable at all – it’s similar to something likeecho "<p>Hello ".$username."!</p>";in PHP (this can get arbitrarily ugly).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:
Next, dict lookup:
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:
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.