带有可选占位符的 string.format() [英] string.format() with optional placeholders

查看:22
本文介绍了带有可选占位符的 string.format()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have the following Python code (I'm using Python 2.7.X):

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

我收到 KeyError 异常,因为未指定中间"(这是预期的).但是,我希望所有这些占位符都是可选的.如果未指定这些命名参数,我希望删除占位符.所以上面打印的字符串应该是:

I get a KeyError exception because 'middle' is not specified (this is expected). 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!

推荐答案

这是一种选择:

from collections import defaultdict

my_csv = '{d[first]},{d[middle]},{d[last]}'
print( my_csv.format( d=defaultdict(str, first='John', last='Doe') ) )

这篇关于带有可选占位符的 string.format()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆