Python在字符串中插入变量

时间:2016-04-21 14:08:22

标签: python

在python中我有一个下面的字符串

body='{"mode":"sync","message":"43b","messages":[{"node1":44,"node2":45}]}'

我需要使用变量4445替换硬编码值v1v2

我尝试使用格式选项,但似乎无法正常工作

5 个答案:

答案 0 :(得分:2)

您需要字符串格式:

>>> v1 = 44
>>> v2 = 45
>>> body='{"mode":"sync","message":"43b","messages":[{"node1":%s,"node2":%s}]}' % (v1, v2)
'{"mode":"sync","message":"43b","messages":[{"node1":40,"node2":45}]}'

答案 1 :(得分:1)

使用json模块:

{"mode": "sync", "message": "43b", "messages": [{"node2": "bar", "node1": "foo"}]}

输出:

public static void main(String args[]) throws FileNotFoundException {
    // create our model and a test generation algorithm
    Tester tester = new RandomTester(new FSM());
    // build the complete FSM graph for our model, just to ensure
    // that we get accurate model coverage metrics.
    tester.buildGraph();
    // set up our favourite coverage metric
    CoverageMetric trCoverage = new TransitionCoverage();
    tester.addListener(trCoverage);
    // ask to print the generated tests
    //tester.addListener("verbose");
    // generate a small test suite of 20 steps (covers 4/5 transitions)
    tester.generate(20);
    //tester.getModel().printMessage(trCoverage.getName() + " was " + trCoverage.toString());

    GraphListener gl = tester.buildGraph();
    gl.printGraphDot("/Users/mahsaabbasian/Documents/workspace/ModelJunit/src/modelJunit/file.dot");
    InspectableGraph graph1 = gl.getGraph();
    DirectedDFS dfs = new DirectedDFS();
    dfs.execute(graph1);
    dfs.isDone();
    Vertex v = graph1.aVertex();
    dfs.dfsVisit(v);

}

答案 2 :(得分:1)

您可以将此字符串转换为dict,然后您可以将其替换为:

body='{"mode":"sync","message":"43b","messages":[{"node1":44,"node2":45}]}'
import json
body = json.loads(body)
print body
v1 = "aaa"
v2 = "bbb"
body["messages"][0]["node1"] = v1
body["messages"][0]["node2"] = v2
body = json.dumps(body)
print body

结果:

  

{“message”:“43b”,“messages”:[{“node1”:“aaa”,“node2”:“bbb”}],   “mode”:“sync”}

答案 3 :(得分:-2)

v1 = 44
v2 = 45
body='{"mode":"sync","message":"43b","messages":[{"node1":%s,"node2":%s}]}' % (v1, v2)
如果你想要在v1和/或v2不是整数的情况下引发TypeError,请使用%d而不是%s

答案 4 :(得分:-2)

下面是python中一个简单的字符串格式化方法,用于在字符串

中插入变量

a =“嗨,我的名字是{name}”; b = a.format(name ='cool geek')