Python 2.6 introduced the str.format() method with a slightly different syntax from the existing %
operator. Which is better and for what situations?
Pyt
One situation where %
may help is when you are formatting regex expressions. For example,
'{type_names} [a-z]{2}'.format(type_names='triangle|square')
raises IndexError
. In this situation, you can use:
'%(type_names)s [a-z]{2}' % {'type_names': 'triangle|square'}
This avoids writing the regex as '{type_names} [a-z]{{2}}'
. This can be useful when you have two regexes, where one is used alone without format, but the concatenation of both is formatted.