Python格式化对象的字符串文字

时间:2016-11-23 20:22:59

标签: python python-3.6

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'

2 个答案:

答案 0 :(得分:0)

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

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

还应该注意f-strings和str.format允许的语法之间有subtle differences,所以前者并不是后者的超集。

答案 1 :(得分:0)

Nope,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表达式的格式化。

相关问题