string % dictionary question

Alex Martelli aleaxit at
Tue Sep 14 13:43:44 CEST 2004

Sam Sungshik Kong <ssk at> wrote:

> Hello, group!
> <code>
> >>> di={}
> >>> di["test"]=None
> >>> s="%(test)s" % di
> >>> s
> 'None'
> </code>
> I want the result to be just empty string when the dictionary value is None.
> Is there a good way?

class Translator(object):
  def __init__(self, d, t=''):
    self.d = d
    self.t = t
  def __getitem__(self, n): 
    result = self.d.get(n)
    if result is None: result = self.t
    return result

s = 'before%(test)safter' % Translator({})

will leave 'beforeafter' in s, as the missing key gets treated just like
a None.  If you want this to raise, and only explicit None values to get
translated, change the first line of __getitem__ into


More information about the Python-list mailing list