Python string interpolation using dictionary and strings

后端 未结 8 1237
半阙折子戏
半阙折子戏 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.

提交回复
热议问题