0

I am trying to concatenate a multi line string with a single line in python and it's giving me an invalid syntax error.

 authHeader = '<header></header>'

 reqBody = '<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope">' 
                 + authHeader + 
                '''<s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
                <GetSnapshotUri xmlns="http://www.onvif.org/ver10/media/wsdl"><ProfileToken>quality_h264</ProfileToken></GetSnapshotUri>
                </s:Body>
                </s:Envelope>
                ''' 
SuperBiasedMan
  • 9,814
  • 10
  • 45
  • 73

1 Answers1

2

No need to use the + operator to concatenate strings you want to spread out over multiple lines for better readability. Just do something like this:

s = (
    "my very long string"
    "that spans multiple lines"
)

The parser will correctly deal with this and it is part of the Python grammar (String Literal Concatentation. Turning larger strings into sequences of code like this often ends up being far more readable.

For more info, see the Python docs on Strings which states:

This feature is particularly useful when you want to break long strings:

>>> text = ('Put several strings within parentheses '
            'to have them joined together.')
>>> text
'Put several strings within parentheses to have them joined together.'
James Mills
  • 18,669
  • 3
  • 49
  • 62