string.format() with optional placeholders

void.pointer picture void.pointer · Jun 13, 2012 · Viewed 16.8k times · Source

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

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!

Answer

Andrew Clark picture Andrew Clark · Jun 13, 2012

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