簡體   English   中英

帶有可選占位符的 string.format()

[英]string.format() with optional placeholders

我有以下 Python 代碼(我使用的是 Python 2.7.X):

my_csv = '{first},{middle},{last}'
print( my_csv.format( first='John', last='Doe' ) )

我收到KeyError異常,因為未指定“中間”(這是預期的)。 但是,我希望所有這些占位符都是可選的。 如果未指定這些命名參數,我希望刪除占位符。 所以上面打印的字符串應該是:

John,,Doe

是否有內置功能使這些占位符可選,或者是否需要更深入的工作? 如果是后者,如果有人可以向我展示最簡單的解決方案,我將不勝感激!

這是一種選擇:

from collections import defaultdict

my_csv = '{d[first]},{d[middle]},{d[last]}'
print( my_csv.format( d=defaultdict(str, first='John', last='Doe') ) )
"It does{cond} contain the the thing.".format(cond="" if condition else " not")

我想我會添加這個,因為自從提出這個問題以來它一直是一個功能,這個問題仍然在谷歌結果的早期彈出,並且這個方法直接內置到 python 語法中(不需要導入或自定義類)。 這是一個簡單的快捷條件語句 它們易於閱讀(保持簡單時),並且它們短路通常很有幫助。

這是使用字符串插值運算符%的另一個選項:

class DataDict(dict):
    def __missing__(self, key):
        return ''

my_csv = '%(first)s,%(middle)s,%(last)s'
print my_csv % DataDict(first='John', last='Doe')  # John,,Doe

或者,如果您更喜歡使用更現代的str.format()方法,下面的方法也可以使用,但不太自動,因為您將提前明確定義每個可能的占位符(盡管您可以修改DataDict.placeholders on -如果需要的話):

class DataDict(dict):
    placeholders = 'first', 'middle', 'last'
    default_value = ''
    def __init__(self, *args, **kwargs):
        self.update(dict.fromkeys(self.placeholders, self.default_value))
        dict.__init__(self, *args, **kwargs)

my_csv = '{first},{middle},{last}'
print(my_csv.format(**DataDict(first='John', last='Doe')))  # John,,Doe

我遇到了和你一樣的問題,決定創建一個庫來解決這個問題: pyformatting
這是您的 pyformatting 問題的解決方案:

>>> from pyformatting import defaultformatter
>>> default_format = defaultformatter(str)
>>> my_csv = '{first},{middle},{last}'
>>> default_format(my_csv, first='John', last='Doe')
'John,,Doe'

唯一的問題是 pyformatting 不支持 python 2。pyformatting 支持 python 3.1+ 如果我看到任何關於需要 2.7 支持的反饋,我想我會添加該支持。

暫無
暫無

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

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