partial string formatting

前端 未结 21 1100
野的像风
野的像风 2020-11-28 04:30

Is it possible to do partial string formatting with the advanced string formatting methods, similar to the string template safe_substitute() function?

F

21条回答
  •  天涯浪人
    2020-11-28 05:18

    My suggestion would be the following (tested with Python3.6):

    class Lazymap(object):
           def __init__(self, **kwargs):
               self.dict = kwargs
    
           def __getitem__(self, key):
               return self.dict.get(key, "".join(["{", key, "}"]))
    
    
    s = '{foo} {bar}'
    
    s.format_map(Lazymap(bar="FOO"))
    # >>> '{foo} FOO'
    
    s.format_map(Lazymap(bar="BAR"))
    # >>> '{foo} BAR'
    
    s.format_map(Lazymap(bar="BAR", foo="FOO", baz="BAZ"))
    # >>> 'FOO BAR'
    

    Update: An even more elegant way (subclassing dict and overloading __missing__(self, key)) is shown here: https://stackoverflow.com/a/17215533/333403

提交回复
热议问题