我不知道';我得不到什么';这是format()和。。。(python)
困惑的新手。使用以下各项有什么区别:我不知道';我得不到什么';这是format()和。。。(python),python,string,variables,python-3.x,Python,String,Variables,Python 3.x,困惑的新手。使用以下各项有什么区别: print ("So you are {0} years old".format(age)) 及 两者都有效 前者更方便。想象一下,如果你有很多参数,你会得到如下结果: print ("So your name is ", firstname, " ", lastname, " and you are ", age, " years old") 读和写都很痛苦。因此,format方法可以帮助您编写更清晰、可读性更强的字符串。事实上,两者之间存在巨大差异。
print ("So you are {0} years old".format(age))
及
两者都有效 前者更方便。想象一下,如果你有很多参数,你会得到如下结果:
print ("So your name is ", firstname, " ", lastname, " and you are ", age, " years old")
读和写都很痛苦。因此,format方法可以帮助您编写更清晰、可读性更强的字符串。事实上,两者之间存在巨大差异。前者使用string的方法创建字符串。后者,将几个参数传递给函数,函数将连接它们,并在它们之间添加一个空格(默认值) 前者功能更强大,例如,您可以使用它来完成以下任务:
# 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中的新标准
>>> 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\u spec
指定的不同表示法将同一对象转换为字符串<代码>打印
使用\uuuuu str\uuuuu
或\uuuu repr\uuuu
(如果未定义前者)<代码>格式()也可以使用\uuuuu str\uuuuuu
,\uuuu repr\uuuuuu
,如果未定义\uuuuu格式
在Python2中,您还可以定义\uuuuuUnicode\uuuu
方法:
>>> 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(“仔细看……它们实际上并不相同。字符串格式可以在更多的上下文中使用,而不仅仅是print
。在后一种情况下,print()
函数正在做这项工作,因此语法除了在print()中之外,在任何地方都不起作用。)
函数。在前一种情况下,字符串实例方法正在执行此项工作,因此可以在任何有字符串的地方工作。删除打印
,看看什么更有意义。相关:例如,日志记录
模块使用%
格式。没错,我想我在文档中的某个地方读到了,但证据提示c谢谢你的更正,我将编辑答案:)这些多余的空格不是必需的;print()
已经插入了。
>>> 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