2012-04-15 67 views
5

最近,我發現''.format函數非常有用,因爲它比起%格式可以提高很多可讀性。 努力實現簡單的字符串格式:如我所料python的「.format」函數

data = {'year':2012, 'month':'april', 'location': 'q2dm1'} 

year = 2012 
month = 'april' 
location = 'q2dm1' 
a = "year: {year}, month: {month}, location: {location}" 
print a.format(data) 
print a.format(year=year, month=month, location=location) 
print a.format(year, month, location) 

雖然兩個第一印DO方式(是的,something=something長相醜陋,但是這只是一個例子),最後一個將提高KeyError: 'year'。 python有沒有什麼竅門可以創建字典,所以它會自動填充鍵和值,例如somefunc(year, month, location)會輸出{'year':year, 'month': month, 'location': location}

我很新的python,並找不到任何有關此主題的信息,但是這樣的技巧將大大改善和縮小我的當前代碼。

提前致謝,請原諒我的英語。

回答

6

第一print應該是

print a.format(**data) 

此外,如果你正在尋找一些捷徑,你可以寫一個像,沒什麼大的區別。

def trans(year, month, location): 
    return dict(year=year, month=month, location=location) 
+0

似乎沒有辦法縮小這個重複的代碼:)功能是好的,這是我做的,實際上,但後來我發現很難維持,因爲與我需要在很多地方修改代碼,結果甚至比實際用手製造字典更糟。 – 2012-04-15 08:09:03

+0

@duke_nukem是的這取決於你的實際使用情況。代碼很好,格式API足夠清晰。如果你要做什麼像'format(* args,** kwargs)',它也可以完成,但我認爲它不會讓事情變得簡單。 – okm 2012-04-15 08:15:42

1

可以使用dict()調用:

dict(year=yeah, month=month, location=location) 

當傳遞關鍵字參數就創建了一個包含您指定爲kwargs元素的字典。

如果你不想指定參數名,使用的.format()位置風格:

>>> a = 'year {0} month {1} location {2}' 
>>> print a.format(2012, 'april', 'abcd') 
year 2012 month april location abcd 

但是,如果你嘗試做類似於compact() in PHP不(創建一個字典映射變量名的東西它的值沒有分別指定名稱和變量),請不要。它只會導致醜陋的無法讀取的代碼,無論如何都需要討厭的黑客。

+0

是的,我知道字典的()但我試圖避免不必要的代碼並將其縮小一點。 .format可以接受你的選項,而不用dict()。謝謝。 – 2012-04-15 07:56:29

+0

謝謝,它接近我所需要的,但是有10-12個參數,它很難通過索引進行導航。 – 2012-04-15 08:01:30

+0

在這種情況下,你應該使用dict語法。然而,根據你想要做什麼,考慮使用一個真正的模板引擎,如[jinja2](http://jinja.pocoo.org/)。 – ThiefMaster 2012-04-15 08:02:09

1

你可以通過locals()

a.format(**locals()) 

當然,這有問題:你將不得不通過在當地人的一切,它可以是很難理解改名的效果或刪除變量。

一個更好的辦法是:

a.format(**{k:v for k,v in locals() if k in ('year', 'month')}) 
# or; note that if you move the lambda expression elsewhere, you will get a different result 
a.format(**(lambda ld = locals(): {k:ld[k] for k in ('year', 'month')})()) 

但是,這不是任何更簡潔,除非你有一個功能(當然必須採取的字典參數)包起來。

3
data = {'year':2012, 'month':'april', 'location': 'q2dm1'} 
a = "year: {year}, month: {month}, location: {location}" 

print a.format(**data) 

..你在找什麼。它的功能與.format(year=data['year'], ...)或您提供的其他示例完全相同。

雙asterix的東西是一個很難搜索的東西,所以它通常被稱爲「kwargs」。這裏有一個good SO question on this syntax

0

截至Python 3.6,你也可以使用新的Formatted string literals (f-strings),您可以用變量使用:

year = 2012 
month = 'april' 
location = 'q2dm1' 
a = f"year: {year}, month: {month}, location: {location}" 
print(a) 

字典

data = {'year': 2012, 'month': 'april', 'location': 'q2dm1'} 
a = f"year: {data['year']}, month: {data['month']}, location: {data['location']}" 
print(a) 

注意字符串文字前的f前綴。

PEP 498: Formatted string literals

格式化字符串文字的前綴爲 'f' 和類似於由str.format接受 格式字符串()。它們包含用花括號包圍的替代品 。替換字段 表達式,它在運行時進行評估,然後格式化使用 格式()協議:

>>> 
>>> name = "Fred" 
>>> f"He said his name is {name}." 
'He said his name is Fred.' 
>>> width = 10 
>>> precision = 4 
>>> value = decimal.Decimal("12.34567") 
>>> f"result: {value:{width}.{precision}}" # nested fields 
'result:  12.35' 

...