【发布时间】:2021-03-22 08:55:41
【问题描述】:
我有一个字符串
start = """<?xml version="1.0" encoding="utf-8" ?><soap:Envelope \
xmlns="http://tempuri.org/"> \
<UserName>username</UserName><Password>password</Password>\
xmlns="http://tempuri.org/"><oShipData>"""
我想为用户名和密码使用环境变量,而不是在代码中硬编码,我尝试了这个
import os
start = """<?xml version="1.0" encoding="utf-8" ?><soap:Envelope \
xmlns="http://tempuri.org/"> \
<UserName>"""os.environ["username"]"""</UserName><Password>"""os.environ["password"]"""</Password>
xmlns="http://tempuri.org/"><oShipData>"""
但这给了我一个错误:
"errorMessage": "Syntax error in module 'test': invalid syntax (test.py, line 5)",
"errorType": "Runtime.UserCodeSyntaxError"
如何转义字符串并从字符串中的os.environ 动态获取值?
【问题讨论】:
-
只要在两边加上
+就可以了。有很多方法可以达到所需的结果,看看str.format()。您的数据是 XML 格式的,所以最好使用xml.etree来构建 XML 对象。 -
这能回答你的问题吗? Multiline f-string in Python
-
@RandomDavis ,我尝试在我的代码中使用类似 f"house_bill_nbr = '{house_bill_nbr}'" 的格式,但由于这是 XML,它不接受这种格式
标签: python python-3.x string environment-variables string-formatting