-2

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

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

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

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

>> print("{a[:2]}".format(a="abcd")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: string indices must be integers

有没有办法在字符串对象上获得新格式化字符串文字的功能?

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

2 回答 2

0

str.format语法不支持也不会支持较新的 f 字符串将支持的所有表达式。您必须手动评估字符串之外的切片表达式并将其提供给格式函数:

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

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

于 2016-11-23T20:45:35.683 回答
0

不,在应用它们之前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)可能会像a[:':']我猜的那样被评估。

这是出现的原因之一f-strings,以支持任何 Python 表达式的格式化需求。

于 2016-11-23T21:16:53.403 回答