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'