Python根据字典中的值返回格式化字符串

时间:2017-06-11 00:34:38

标签: python string-formatting

在Python中,我有一个脚本,它从名为1或更多变量的外部源接收输入,然后在PLC上查找当前值并将它们返回给客户端。

在脚本上,我定义了所有可能的变量以及要显示给客户端的所需格式和单位。

given_variable = "temp1"  #Client needs current value of temp1
vars_format = {
    "temp1":["%0.1f","C"],
    "press1":["%0.2f","bar"],
    "temp2":["%d","K"],
    "distance":["%0.3f","km"],
    "switch":["%d",""]
}

# Logic for finding current plc_value of given_variable
# plc_value is a string that looks like a real number
# ("3.14159"), an integer "3" or a string "Running"

return "%s %s" % ( plc_value, vars_format[ given_variable ][1] )

如何动态(根据字典)以所需格式返回plc_value? 在这个例子中,如何获得" 23.4 C"而不是" 23.39999 C" for" temp1"或" 45.21 bar"而不是" 42.21248 bar" for" press1"?

1 个答案:

答案 0 :(得分:4)

好吧,将您的值应用于vars_format返回的内容:

return "%s %s" % (vars_format[given_variable][0] % plc_value, vars_format[given_variable][1])

但这很丑陋。为什么不直接将所有内容定义为可以基于given_variable交换的优秀源代码字符串:

vars_format = {
    "temp1": "%0.1f C",
    "press1":"%0.2f bar",
    "temp2": "%d K",
    "distance": "%0.3f km",
    "switch": "%d"
}

return vars_format[given_variable] % plc_value

甚至更好,使用str.format()获得更多灵活性和更现代的字符串替换选项。