Python string interpolation using dictionary and strings

后端 未结 8 1193
半阙折子戏
半阙折子戏 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:09

    If you don't want to add the unchanging variables to your dictionary each time, you can reference both the variables and the dictionary keys using format:

    str = "path {path} curr: {curr} prev: {prev}".format(curr=curr, prev=prev, **dict)

    It might be bad form logically, but it makes things more modular expecting curr and prev to be mostly static and the dictionary to update.

    0 讨论(0)
  • 2020-12-28 16:12

    You can also (soon) use f-strings in Python 3.6, which is probably the shortest way to format a string:

    print(f'path: {path} curr: {curr} prev: {prev}')
    

    And even put all your data inside a dict:

    d = {"path": path, "curr": curr, "prev": prev}
    print(f'path: {d["path"]} curr: {d["curr"]} prev: {d["prev"]}')
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-28 16:22

    You can try this:

    data = {"path": "/var/blah",
            "curr": "1.1",
            "prev": "1.0"}
    
    s = "path: %(path)s curr: %(curr)s prev: %(prev)s" % data
    
    0 讨论(0)
  • 2020-12-28 16:24

    You can do the following if you place your data inside a dictionary:

    data = {"path": "/var/blah","curr": "1.1","prev": "1.0"}
    
    "{0}: {path}, {1}: {curr}, {2}: {prev}".format(*data, **data)
    
    0 讨论(0)
  • 2020-12-28 16:26

    Why not:

    mystr = "path: %s curr: %s prev: %s" % (mydict[path], curr, prev)
    

    BTW, I've changed a couple names you were using that trample upon builtin names -- don't do that, it's never needed and once in a while will waste a lot of your time tracking down a misbehavior it causes (where something's using the builtin name assuming it means the builtin but you have hidden it with the name of our own variable).

    0 讨论(0)
提交回复
热议问题