String formatting: % vs. .format vs. string literal

后端 未结 16 2776
青春惊慌失措
青春惊慌失措 2020-11-21 04:18

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

16条回答
  •  后悔当初
    2020-11-21 04:50

    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.

提交回复
热议问题