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'
不可以。根據文檔,這是沒有意義的:https://docs.python.org/3.6/reference/lexical_analysis.html#f-strings就我所見,它是語法糖.format()反正。 –
你可以用'eval()'在技術上做到這一點。這通常是一個壞主意,但在這種情況下,確保安全性非常困難,因爲格式字符串本身可以包含任意的Python代碼。所以,即使你首先解析字符串('ast.parse()'),並確保它只包含一個格式字符串,那麼這個單一格式字符串與eval()本身一樣危險。 – kindall