These are two very popular ways of formatting a string in Python. One is using a dict:
>>> 'I will be %(years)i on %(month)s %(day)i' % {'years': 21, 'month': 'January', 'day': 23}
'I will be 21 on January 23'
And the other one using a simple tuple:
>>> 'I will be %i on %s %i' % (21, 'January', 23)
'I will be 21 on January 23'
The first one is way more readable, but the second one is faster to write. I actually use them indistinctly.
What are the pros and cons of each one? regarding performance, readability, code optimization (is one of them transformed to the other?) and anything else you would think is useful to share.
Why
format()is more flexible than%string operationsI think you should really stick to
format()method ofstr, because it is the preferred way to format strings and will probably replace string formatting operation in the future.Furthermore, it has some really good features, that can also combine position-based formatting with keyword-based one:
even the following will work:
There is also one other reason in favor of
format(). Because it is a method, it can be passed as a callback like in the following example:Isn’t it a lot more flexible than string formatting operation?
See more examples on documentation page for comparison between
%operations and.format()method.Comparing tuple-based
%string formatting with dictionary-basedGenerally there are three ways of invoking
%string operations (yes, three, not two) like that:and they differ by the type of
values(which is a consequence of what is the content ofbase_string):it can be a
tuple, then they are replaced one by one, in the order they are appearing in tuple,it can be a
dict(dictionary), then they are replaced based on the keywords,it can be a single value, if the
base_stringcontains single place where the value should be inserted:There are obvious differences between them and these ways cannot be combined (in contrary to
format()method which is able to combine some features, as mentioned above).But there is something that is specific only to dictionary-based string formatting operation and is rather unavailable in remaining three formatting operations’ types. This is ability to replace specificators with actual variable names in a simple manner:
Just for the record: of course the above could be easily replaced by using
format()by unpacking the dictionary like that:Does anyone else have an idea what could be a feature specific to one type of string formatting operation, but not to the other? It could be quite interesting to hear about it.