python-在双引号内添加变量,变量也包含双引号

时间:2019-02-27 07:10:55

标签: python string variables double-quotes single-quotes

我有原始内容,需要如下所示的预期输出。

curl -X POST -H "Content-Type: application/json" https://bitbucket.org/api/2.0/repositories/username/BB_Access/pullrequests -d '{ "title": "Merge dev branch to Master", "source": { "branch": { "name": "Dev" }, "repository": { "full_name": "username/BB_Access" } }, "destination": { "branch": { "name": "master" } }, "close_source_branch": false }'

下面是我尝试过的代码。

import subprocess
BBrepo = "BB_Access"
BBuser = "username"
src_branch = "Dev"
Dest_branch = "master"
pull_command = "curl -X POST -H "'"Content-Type: application/json"'" https://bitbucket.org/api/2.0/repositories/"+BBuser+"/"+BBrepo+"/pullrequests -d '"'{ "title": "python_pull_request", "source": { "branch": { "name": '"' "+src_branch+" }, '"'repository": { "full_name": '"'"+BBuser+"/"+BBrepo+" } }, '"'destination": { "branch": { "name": '"'"+Dest_branch+'"'" } }, '"'close_source_branch": false }'"'"

print pull_command

但是它给出的输出如下

curl -X POST -H "Content-Type: application/json" https://bitbucket.org/api/2.0/repositories/username/BB_Access/pullrequests -d '{ "title": "python_pull_request", "source": { "branch": { "name": ' Dev }, 'repository": { "full_name": 'username/BB_Access } }, 'destination": { "branch": { "name": 'master" } }, 'close_source_branch": false }'

谁能建议我一种获得预期输出的更好方法。

2 个答案:

答案 0 :(得分:1)

我看到两种方式:

  • "(或相反)中使用''
  • 转义为"\""'\''

答案 1 :(得分:0)

您可以尝试以下方法:

import subprocess
BBrepo = "BB_Access"
BBuser = "username"
src_branch = "Dev"
Dest_branch = "master"
pull_command = 'curl -X POST -H "Content-Type: application/json" https://bitbucket.org/api/2.0/repositories/'+BBuser+'/'+BBrepo+'/pullrequests -d \'{ "title": "python_pull_request", "source": { "branch": { "name": '+'"'+src_branch+'"'+' }, "repository": { "full_name": '+'"'+BBuser+'/'+BBrepo+'"'+' } }, "destination": { "branch": { "name": '+'"'+Dest_branch+'"'+' } }, "close_source_branch": false }\''

print(pull_command)

Ang得到:

curl -X POST -H "Content-Type: application/json" https://bitbucket.org/api/2.0/repositories/username/BB_Access/pullrequests -d '{ "title": "python_pull_request", "source": { "branch": { "name": "Dev" }, "repository": { "full_name": "username/BB_Access" } }, "destination": { "branch": { "name": "master" } }, "close_source_branch": false }'