簡體   English   中英

Python 2中的格式化字符串文字

[英]Formatted String Literals in Python 2

在Python 2.7中編寫模塊時,我需要一種方法

name = "Rodrigo"
age = 34
print f"Hello {name}, your age is {age}".format()

盡管我知道我可以做到:

print "Hello {name}, your age is {age}".format(name=name, age=age)

format()將在變量nameage的范圍內查找,將它們轉換為字符串(如果可能)並粘貼到消息中。 我發現這已在Python 3.6+中實現,稱為Formatted String Literals 因此,我想知道(找不到谷歌搜索)是​​否有人對Python 2.7采取了類似的方法

您可以通過組合內置的locals函數和字符串上的format方法來嘗試這種怪異的處理方式:

foo = "asd"
bar = "ghi"

print("{foo} and {bar}".format(**locals())

這是一個自動插入變量的實現。 請注意,它不支持python 3 f字符串具有的任何高級功能(例如屬性訪問):

import inspect

def fformat(string):
    caller_frame = inspect.currentframe().f_back
    names = dict(caller_frame.f_globals, **caller_frame.f_locals)
    del caller_frame
    return string.format(**names)
a = 1
foo = 'bar'
print fformat('hello {a} {foo}')
# output: "hello 1 bar"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM