string % dictionary question

Alex Martelli aleaxit at yahoo.com
Tue Sep 14 07:43:44 EDT 2004


Sam Sungshik Kong <ssk at chol.nospam.net> 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
'result=self.d[n]'.


Alex



More information about the Python-list mailing list