Here are the syntax documents for the "new" format. An example is:
"({:d} goals, ${:d})".format(self.goals, self.penalties)
If both goals and penalties are integers (i.e. their format is approved by default), it can be shortened to:
"({} goals, ${})".format(self.goals, self.penalties)
And since parameters are self fields, there is a way to do this using one argument twice (as @Burhan Khalid noted in the comments):
"({0.goals} goals, ${0.penalties})".format(self)
Clarification:
{} means only the next argument positional with the standard format;{0} means argument with index 0 with standard format;{:d} is the next positional argument with decimal integer format;{0:d} is an argument with index 0 with a decimal integer format.
There are many other things that you can do when choosing an argument (using named arguments instead of positional, access to fields, etc.) and many format options (filling in the number, using thousands separators, displaying the sign or not).). Some other examples:
"({goals} goals, ${penalties})".format(goals=2, penalties=4) "({goals} goals, ${penalties})".format(**self.__dict__) "first goal: {0.goal_list[0]}".format(self) "second goal: {.goal_list[1]}".format(self) "conversion rate: {:.2f}".format(self.goals / self.shots) # '0.20' "conversion rate: {:.2%}".format(self.goals / self.shots) # '20.45%' "conversion rate: {:.0%}".format(self.goals / self.shots) # '20%' "self: {!s}".format(self) # 'Player: Bob' "self: {!r}".format(self) # '<__main__.Player instance at 0x00BF7260>' "games: {:>3}".format(player1.games) # 'games: 123' "games: {:>3}".format(player2.games) # 'games: 4' "games: {:0>3}".format(player2.games) # 'games: 004'
Note. . As others noted, the new format does not replace the first, both are available both in Python 3 and in newer versions of Python 2. Some may say that this is a matter of preference, but IMHO is more expressive than the older one and should be used when writing new code (of course, if it is not aimed at older environments).
mgibsonbr Dec 19 2018-12-12T00: 00Z
source share