我不明白format()和...的区别是什么(python)

3 投票
3 回答
1926 浏览
提问于 2025-04-18 05:20

这里有个刚入门的小伙伴在困惑。他想知道使用:

print ("So you are {0} years old".format(age))

print ("So you are", age, "years old")

有什么区别。

其实这两种写法都能正常工作。

3 个回答

0

前者使用起来更方便。想象一下,如果你有很多参数,最后的代码可能会变成这样:

print ("So your name is ", firstname, " ", lastname, " and you are ", age, " years old")

这样写起来和看起来都很麻烦。所以,格式化方法就是为了帮助你写出更简洁、更易读的字符串。

2
>>> class Age:
...     def __format__(self, format_spec):
...         return "{:{}}".format("format", format_spec)
...     def __str__(self):
...         return "str"
... 
>>> age = Age()
>>> print(age)
str
>>> print("{:s}".format(age))
format

format() 这个函数可以把同一个对象用不同的方式转换成字符串,这种方式是由 format_spec 来指定的。print 函数会使用 __str__ 或者 __repr__,如果 __str__ 没有定义的话。format() 也可以使用 __str____repr__,如果 __format__ 没有定义的话。

在 Python 2 中,你还可以定义 __unicode__ 方法:

>>> class U:
...   def __unicode__(self):
...       return u"unicode"
...   def __str__(self):
...       return "str"
...   def __repr__(self):
...       return "repr"
... 
>>> u = U()
>>> print(u"%s" % u)
unicode
>>> print(u)
str
>>> print(repr(u))
repr
>>> u
repr

Python 3 里还有一个内置函数 ascii(),它的作用类似于 repr(),不过它只会输出 ASCII 字符的结果:

>>> print(ascii(""))
'\U0001f40d'

可以查看 U+1F40D SNAKE

format() 使用的是 格式规范小语言,而不是运行各种转换成字符串的函数。

一个对象可以自己定义一种 format_spec 语言,比如 datetime 允许使用 strftime 格式:

>>> from datetime import datetime
>>> "{:%c}".format(datetime.utcnow())
'Sun May  4 18:51:18 2014'
7

其实这两者之间有很大的区别。前者使用字符串的 format 方法来创建字符串。而后者则是把几个参数传给 print 函数,这样会把它们连接在一起,中间默认会加一个空格。

前者功能更强大,比如你可以使用 格式语法 来做一些事情,比如:

# trunc a float to two decimal places
>>> '{:.2f}'.format(3.4567)
'3.46'

# access an objects method
>>> import math
>>> '{.pi}'.format(math)
'3.141592653589793'

这有点像早期版本的 Python 中使用 printf 风格的格式,使用 % 操作符(例如:"%d" % 3)。现在推荐使用 str.format(),它比 % 操作符更好,是 Python 3 的新标准。

撰写回答