Python 3 中的字符串格式化 [英] String formatting in Python 3

本文介绍了Python 3 中的字符串格式化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!


我在 Python 2 中这样做:

I do this in Python 2:

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

Python 3 版本是什么?

What is the Python 3 version of this?

我尝试在网上搜索示例,但一直得到 Python 2 版本.

I tried searching for examples online but I kept getting Python 2 versions.


这里是 有关新"格式语法的文档.一个例子是:

Here are the docs about the "new" format syntax. An example would be:

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

如果 goalspenalties 都是整数(即它们的默认格式是可以的),则可以缩短为:

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 在评论中指出的那样):

And since the parameters are fields of self, there's also a way of doing it using a single argument twice (as @Burhan Khalid noted in the comments):

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


  • {} 表示只是下一个位置参数,默认格式;
  • {0} 表示索引为0的参数,默认格式;
  • {:d} 是下一个位置参数,十进制整数格式;
  • {0:d} 是索引为 0 的参数,采用十进制整数格式.
  • {} means just the next positional argument, with default format;
  • {0} means the argument with index 0, with default format;
  • {:d} is the next positional argument, with decimal integer format;
  • {0:d} is the argument with index 0, with decimal integer format.


There are many others things you can do when selecting an argument (using named arguments instead of positional ones, accessing fields, etc) and many format options as well (padding the number, using thousands separators, showing sign or not, etc). 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(  # 'games: 123'
"games: {:>3}".format(  # 'games:   4'
"games: {:0>3}".format( # 'games: 004'


注意:正如其他人指出的那样,新格式不会取代前者,这两种格式都可用于 Python 3 和较新版本的 Python 2.有些人可能会说这是一个偏好问题,但恕我直言,新的比旧的更具表现力,并且应该在编写新代码时使用(当然,除非它针对旧环境).

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 中的字符串格式化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

登录 关闭
发送“验证码”获取 | 15天全站免登陆