Omn*_*yte 2 python string variables quotes variable-assignment
我正在编辑一个脚本,该脚本对openstack keystone进行身份验证以获取令牌.API-Call有效,但我想使用变量而不是直接值来使其更具可读性和可重用性.但问题是值必须在引号(")中,我无法弄清楚如何做到这一点.我发现一些代码示例[1],[2]一般在字符串中使用变量但是我需要使用某种转义序列将值放在引号中.
目前我的字符串赋值如下:
params = '{"auth":{"passwordCredentials":{"username":"nodermatt", "password":"feelfree"}, "tenantId":"4"}}'
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,用户名,密码和tenantID的值都在引号中,我希望它用变量替换它们:
osuser = "nodermatt"
ospassword = "feelfree"
ostenant = "4"
params = '{"auth":{"passwordCredentials":{"username":osuser, "password":ospassword}, "tenantId":ostenant}}'
Run Code Online (Sandbox Code Playgroud)
如果可以解决这个"问题",我会很高兴.
PS:如果我在Google上错过了与我的问题匹配的帖子或搜索结果,我会非常感谢这个链接.
提前致谢!最好的问候,尼古拉斯
[1] Python中的子进程添加变量
对于这种特殊情况,最简单的解决方案是首先定义Python字典,然后使用json.dumps()它将其转换为JSON:
osuser = "nodermatt"
ospassword = "feelfree"
ostenant = "4"
d = {"auth":
{"passwordCredentials": {"username": osuser, "password": ospassword},
"tenantId": ostenant}}
params = json.dumps(d)
Run Code Online (Sandbox Code Playgroud)