Search code examples
pythonpython-3.xstringenvironment-variablesstring-formatting

Use environmental variables in between strings?


I have a string

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>"""

I want to use environmental variables for username and password, instead of hardcoding them in the code, I tried this

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>"""

But this gives me an error:

"errorMessage": "Syntax error in module 'test': invalid syntax (test.py, line 5)",
    "errorType": "Runtime.UserCodeSyntaxError"

How can I escape the strings and dynamically get values from os.environ within the strings?


Solution

  • You can't just put the string and the code next to another, you muse concatenate them with a +

    start = """
    <?xml version="1.0" encoding="utf-8" ?>
        <soap:Envelope xmlns="http://tempuri.org/"> 
            <UserName>""" + os.environ["username"] + """</UserName>
            <Password>""" + os.environ["password"] + """</Password>
        <oShipData>"""