对象的Python格式字符串文本

2024-05-18 14:30:29 发布

您现在位置:Python中文网/ 问答频道 /正文

Python3.6的一个非常酷的新特性是格式化字符串文本(https://docs.python.org/3.6/whatsnew/3.6.html#whatsnew36-pep498)的实现。在

不幸的是,它的行为不像众所周知的format()函数:

>> a="abcd"
>> print(f"{a[:2]}")
>> 'ab'

如您所见,切片是可能的(实际上所有的python函数都在字符串上)。 但是format()不能用于切片:

^{pr2}$

有一种新的字符串功能吗??在

>> string_object = "{a[:2]}"   # may also be comming from a file
>> # some way to get the result 'ab' with 'string_object'

Tags: 函数字符串httpsorg文本formatdocsstring
2条回答

str.format语法现在和将来都不支持新的f-string所支持的全部表达式。您必须在字符串外部手动计算切片表达式,并将其提供给format函数:

a = "abcd"
string_object = "{a}".format(a = a[:2])

还应该注意,在f-strings允许的语法和str.format之间存在{a1},因此前者严格来说不是后者的超集。在

不,str.format尝试在应用索引之前先将其强制转换为str,这就是为什么会出现这样的错误;它试图用str索引为字符串建立索引:

a = "abcd" 
>>> a[:'2']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: slice indices must be integers or None or have an __index__ method

它真的不适用于这样的情况;"{a[::]}".format(a=a)可能也会被评估为{}。在

这就是f-strings产生的原因之一,为了支持任何Python表达式的格式化愿望。在

相关问题 更多 >

    热门问题