Python string interpolation using dictionary and strings

后端 未结 8 1195
半阙折子戏
半阙折子戏 2020-12-28 15:49

Given:

dict = {\"path\": \"/var/blah\"}
curr = \"1.1\"
prev = \"1.0\"

What\'s the best/shortest way to interpolate the string to generate t

8条回答
  •  被撕碎了的回忆
    2020-12-28 16:14

    And of course you could use the newer (from 2.6) .format string method:

    >>> mydict = {"path": "/var/blah"}
    >>> curr = "1.1"
    >>> prev = "1.0"
    >>>
    >>> s = "path: {0} curr: {1} prev: {2}".format(mydict['path'], curr, prev)
    >>> s
    'path: /var/blah curr: 1.1 prev: 1.0'   
    

    Or, if all elements were in the dictionary, you could do this:

    >>> mydict = {"path": "/var/blah", "curr": 1.1, "prev": 1.0}
    >>> "path: {path} curr: {curr} prev: {prev}".format(**mydict)
    'path: /var/blah curr: 1.1 prev: 1.0'
    >>>
    

    From the str.format() documentation:

    This method of string formatting is the new standard in Python 3.0, and should be preferred to the % formatting described in String Formatting Operations in new code.

提交回复
热议问题