Python string interpolation using dictionary and strings

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

    Maybe:

    path = dict['path']
    str = "path: %(path)s curr: %(curr)s prev: %(prev)s" % locals()
    

    I mean it works:

    >>> dict = {"path": "/var/blah"}
    >>> curr = "1.1"
    >>> prev = "1.0"
    >>> path = dict['path']
    >>> str = "path: %(path)s curr: %(curr)s prev: %(prev)s" % locals()
    >>> str
    'path: /var/blah curr: 1.1 prev: 1.0'
    

    I just don't know if you consider that shorter.

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

    Update 2016: As of Python 3.6 you can substitute variables into strings by name:

    >>> origin = "London"
    >>> destination = "Paris"
    >>> f"from {origin} to {destination}"
    'from London to Paris'
    

    Note the f" prefix. If you try this in Python 3.5 or earlier, you'll get a SyntaxError.

    See https://docs.python.org/3.6/reference/lexical_analysis.html#f-strings

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