partial string formatting

前端 未结 21 1026
野的像风
野的像风 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:03

    If you'd like to unpack a dictionary to pass arguments to format, as in this related question, you could use the following method.

    First assume the string s is the same as in this question:

    s = '{foo} {bar}'
    

    and the values are given by the following dictionary:

    replacements = {'foo': 'FOO'}
    

    Clearly this won't work:

    s.format(**replacements)
    #---------------------------------------------------------------------------
    #KeyError                                  Traceback (most recent call last)
    # in ()
    #----> 1 s.format(**replacements)
    #
    #KeyError: 'bar'
    

    However, you could first get a set of all of the named arguments from s and create a dictionary that maps the argument to itself wrapped in curly braces:

    from string import Formatter
    args = {x[1]:'{'+x[1]+'}' for x in Formatter().parse(s)}
    print(args)
    #{'foo': '{foo}', 'bar': '{bar}'}
    

    Now use the args dictionary to fill in the missing keys in replacements. For python 3.5+, you can do this in a single expression:

    new_s = s.format(**{**args, **replacements}}
    print(new_s)
    #'FOO {bar}'
    

    For older versions of python, you could call update:

    args.update(replacements)
    print(s.format(**args))
    #'FOO {bar}'
    

提交回复
热议问题