Python 3中的字符串格式设置

我在 Python 2中这样做:

"(%d goals, $%d)" % (self.goals, self.penalties)

这个版本的 Python3是什么?

我尝试在网上搜索示例,但我一直得到 Python2版本。

113168 次浏览

这行代码在 Python 3中就是这样工作的。

>>> sys.version
'3.2 (r32:88445, Oct 20 2012, 14:09:29) \n[GCC 4.5.2]'
>>> "(%d goals, $%d)" % (self.goals, self.penalties)
'(1 goals, $2)'

Here are 那些文件 about the "new" format syntax. An example would be:

"({:d} goals, ${:d})".format(self.goals, self.penalties)

If both goals and penalties are integers (i.e. their default format is ok), it could be shortened to:

"({} goals, ${})".format(self.goals, self.penalties)

而且因为参数是 self的字段,所以还有一种方法可以使用一个参数执行两次操作(如@Burhan Khalid 在评论中指出的那样) :

"({0.goals} goals, ${0.penalties})".format(self)

Explaining:

  • {} means just the next positional argument, with default format;
  • {0}是指带有指数 0的参数,具有默认格式;
  • {:d}是下一个位置参数,采用十进制整数格式;
  • {0:d}是带有索引 0的参数,其格式为十进制整数。

在选择参数时,还有许多其他事情可以做(使用命名参数而不是位置参数,访问字段等) ,还有许多格式选项(填充数字,使用数千个分隔符,显示符号或不显示符号等)。其他一些例子:

"({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 pointed out, the new format does not supersede the former, both are available both in Python 3 and the newer versions of Python 2 as well. Some may say it's a matter of preference, but IMHO the newer is much more expressive than the older, and should be used whenever writing new code (unless it's targeting older environments, of course).

Python 3.6现在支持 PEP 498中的速记字符串内插:

f"({self.goals} goals, ${self.penalties})"

这类似于以前的 .format标准,但是可以让你轻松地做 like:

>>> width = 10
>>> precision = 4
>>> value = decimal.Decimal('12.34567')
>>> f'result: {value:{width}.{precision}}'
'result:      12.35'

我喜欢这个方法

my_hash = {}
my_hash["goals"] = 3 #to show number
my_hash["penalties"] = "5" #to show string
print("I scored %(goals)d goals and took %(penalties)s penalties" % my_hash)

注意括号中分别附加的 d 和 s。

产出将包括:

I scored 3 goals and took 5 penalties

“ f-string” 可以使用,因为 Python 3.6:

f'({self.goals} goals, ${self.penalties})'