pythonstring-formattingtemplate-variables

string.format() with optional placeholders


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!


Solution

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