简体   繁体   English

带有可选占位符的 string.format()

[英]string.format() with optional placeholders

I have the following Python code (I'm using Python 2.7.X):我有以下 Python 代码(我使用的是 Python 2.7.X):

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

I get a KeyError exception because 'middle' is not specified (this is expected).我收到KeyError异常,因为未指定“中间”(这是预期的)。 However, I want all of those placeholders to be optional.但是,我希望所有这些占位符都是可选的。 If those named parameters are not specified, I expect the placeholders to be removed.如果未指定这些命名参数,我希望删除占位符。 So the string printed above should be:所以上面打印的字符串应该是:

John,,Doe

Is there built in functionality to make those placeholders optional, or is some more in depth work required?是否有内置功能使这些占位符可选,或者是否需要更深入的工作? If the latter, if someone could show me the most simple solution I'd appreciate it!如果是后者,如果有人可以向我展示最简单的解决方案,我将不胜感激!

Here is one option:这是一种选择:

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")

Thought I'd add this because it's been a feature since the question was asked, the question still pops up early in google results, and this method is built directly into the python syntax (no imports or custom classes required).我想我会添加这个,因为自从提出这个问题以来它一直是一个功能,这个问题仍然在谷歌结果的早期弹出,并且这个方法直接内置到 python 语法中(不需要导入或自定义类)。 It's a simple shortcut conditional statement .这是一个简单的快捷条件语句 They're intuitive to read (when kept simple) and it's often helpful that they short-circuit .它们易于阅读(保持简单时),并且它们短路通常很有帮助。

Here's another option that uses the string interpolation operator % :这是使用字符串插值运算符%的另一个选项:

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

Alternatively, if you prefer using the more modern str.format() method, the following would also work, but is less automatic in the sense that you'll have explicitly define every possible placeholder in advance (although you could modify DataDict.placeholders on-the-fly if desired):或者,如果您更喜欢使用更现代的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

I faced the same problem as yours and decided to create a library to solve this problem: pyformatting .我遇到了和你一样的问题,决定创建一个库来解决这个问题: pyformatting
Here is the solution to your problem with 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'

The only problem is pyformatting doesn't support python 2. pyformatting supports python 3.1+ If i see any feedback on the need for 2.7 support i think i will add that support.唯一的问题是 pyformatting 不支持 python 2。pyformatting 支持 python 3.1+ 如果我看到任何关于需要 2.7 支持的反馈,我想我会添加该支持。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM