Note that there are some explanatory texts on larger screens.

plurals
  1. POString formatting in python
    text
    copied!<p>Recently I've been doing a lot of music based programming, and as such find myself doing this kind of thing a lot to deal with missing metadata in some songs:</p> <pre><code>default = {'title': 'Unknown title', 'artist': 'unknown Artist'} default.update(song) print '{title} - {artist}'.format(**default) </code></pre> <p>Is there a cleaner way to do this? I tried overriding __missing__ like so but missing keys still throw a KeyError:</p> <pre><code>class Song(dict): # dictionary with some nice stuff to make it nicer def __missing__(self, key): return 'Unknown {key}'.format(key = key) </code></pre> <p>Edit: Sorry I should have been clearer, basically the following must work.</p> <pre><code>s = Song() print '{notAKey}'.format(s) </code></pre> <p>A couple of people have pointed out that the **s are not necessary. </p> <p>Edit 2: I've "solved" my problem, at least to my satisfaction. It's debatable whether or not this is cleaner, but it works for me. </p> <pre><code>from string import Formatter class DefaultFormatter(Formatter): def get_value(self, key, args, kwargs): # Try standard formatting, then return 'unknown key' try: return Formatter.get_value(self, key, args, kwargs) except KeyError: return kwargs.get(key, 'Unknown {0}'.format(key)) class Song(dict): def format(self, formatString): # Convenience method, create a DefaultFormatter and use it f = DefaultFormatter() return f.format(formatString, **self) </code></pre> <p>So the following will return 'Unknown notAKey'</p> <pre><code>k = Song() print k.format('{notAKey}') </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload