Python格式化字符串文字对象
问题描述:
Python3.6非常酷的新功能之一是格式化字符串文字(https://docs.python.org/3.6/whatsnew/3.6.html#whatsnew36-pep498)的实现。Python格式化字符串文字对象
不幸的是,它并没有表现得像众所周知的格式()函数:
>> 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'
答
的str.format
语法不,不支持全系列表达的是较新的F-字符串会。你必须手动评估片表达字符串之外,它提供给格式函数:
a = "abcd"
string_object = "{a}".format(a = a[:2])
还应注意有subtle differences由F-字符串和str.format
允许的语法之间,所以前者并不完全是后者的超集。
答
没有,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表达式的格式化愿望。
不可以。根据文档,这是没有意义的:https://docs.python.org/3.6/reference/lexical_analysis.html#f-strings就我所见,它是语法糖.format()反正。 –
你可以用'eval()'在技术上做到这一点。这通常是一个坏主意,但在这种情况下,确保安全性非常困难,因为格式字符串本身可以包含任意的Python代码。所以,即使你首先解析字符串('ast.parse()'),并确保它只包含一个格式字符串,那么这个单一格式字符串与eval()本身一样危险。 – kindall