問題描述
有沒有辦法用新的格式語法格式化來自函數調用的字符串?例如:
Is there a way to format with the new format syntax a string from a function call? for example:
"my request url was {0.get_full_path()}".format(request)
所以它調用函數get_full_path
函數inside字符串而不是作為格式函數中的參數.
so it calls the function get_full_path
function inside the string and not as a parameter in the format function.
這是另一個可能會更好地表達我的挫敗感的例子,這就是我想要的:
Here is another example that will probably show my frustration better, this is what I would like:
"{0.full_name()} {0.full_last_name()} and my nick name is {0.full_nick_name()}".format(user)
這是我想要避免的:
"{0} and {1} and my nick name is {2}".format(user.full_name(), user.full_last_name(), user.full_nick_name())
推薦答案
Python 3.6 添加了文字字符串插值,它是用 f
前綴編寫的.請參閱 PEP 0498 -- 文字字符串插值.
Python 3.6 adds literal string interpolation, which is written with an f
prefix. See PEP 0498 -- Literal String Interpolation.
這樣可以寫
>>> x = 'hello'
>>> s = f'{x}'
>>> print(s)
hello
應該注意,這些不是實際的字符串,而是表示每次都計算為字符串的代碼.在上面的示例中,s
的類型為 str
,值為 'hello'
.你不能傳遞一個 f
-string,因為它會在使用前被評估為結果 str
(不像 str.format
,但與所有其他字符串文字修飾符一樣,例如 r'hello'
、b'hello'
、'''hello'''
).(PEP 501 -- 通用字符串插值(目前推遲)建議使用字符串將評估為稍后可以進行替換的對象的文字.)
It should be noted that these are not actual strings, but represent code that evaluates to a string each time. In the above example, s
will be of type str
, with value 'hello'
. You can't pass an f
-string around, since it will be evaluated to the result str
before being used (unlike str.format
, but like every other string literal modifier, such as r'hello'
, b'hello'
, '''hello'''
). (PEP 501 -- General purpose string interpolation (currently deferred) suggests a string literal that will evaluate to an object which can take substitutions later.)
這篇關于python字符串格式調用函數的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!