voi*_*ter 17 python string-formatting template-variables
我有以下Python代码(我使用的是Python 2.7.X):
my_csv = '{first},{middle},{last}'
print( my_csv.format( first='John', last='Doe' ) )
Run Code Online (Sandbox Code Playgroud)
我得到一个KeyError例外,因为没有指定'middle'(这是预期的).但是,我希望所有这些占位符都是可选的.如果未指定这些命名参数,我希望删除占位符.所以上面打印的字符串应该是:
John,,Doe
Run Code Online (Sandbox Code Playgroud)
是否有内置功能使这些占位符可选,或者是否需要更深入的工作?如果是后者,如果有人能告诉我最简单的解决方案,我会很感激!
And*_*ark 16
这是一个选项:
from collections import defaultdict
my_csv = '{d[first]},{d[middle]},{d[last]}'
print( my_csv.format( d=defaultdict(str, first='John', last='Doe') ) )
Run Code Online (Sandbox Code Playgroud)
这是使用字符串插值运算符的另一个选项%:
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
Run Code Online (Sandbox Code Playgroud)
或者,如果您更喜欢使用更现代的str.format()方法,下面的方法也可以使用,但是在您预先明确定义每个可能的占位符的意义上(尽管您可以DataDict.placeholders根据需要即时修改)意义上的自动化程度较低:
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
Run Code Online (Sandbox Code Playgroud)
"It does{cond} contain the the thing.".format(cond="" if condition else " not")
Run Code Online (Sandbox Code Playgroud)
以为我要添加它,因为自从提出问题以来,它一直是一个功能,这个问题仍然会在Google搜索结果的早期弹出,并且此方法直接内置在python语法中(不需要导入或自定义类)。这是一个简单的快捷方式条件语句。阅读起来很直观(保持简单),并且将它们短路通常是有帮助的。