Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this Python script have a \ before the multi-line string and what does it do?

In a Python script I'm looking at the string has a \ before it:

print """\
Content-Type: text/html\n
<html><body>
<p>The submited name was "%s"</p>
</body></html>
""" % name

If I remove the \ it breaks. What does it do?

like image 896
Doug Smith Avatar asked Nov 26 '13 18:11

Doug Smith


People also ask

What is a multiline string in Python?

A multiline string in Python begins and ends with either three single quotes or three double quotes. Any quotes, tabs, or newlines in between the “triple quotes” are considered part of the string.

What starts and ends a multiline string Python?

Python multiline string begins and ends with either three single quotes or three double-quotes.


1 Answers

It tells Python to ignore the newline directly following the backslash. The resulting string starts with Content-Type:, not with \nContent-Type::

>>> '''\
This is the first line.
This is the second line.
'''
'This is the first line.\nThis is the second line.\n'
>>> '''
... This is the first line.
... This is the second line.
... '''
'\nThis is the first line.\nThis is the second line.\n'

Note how the two results differ; the first has no \n newline character at the start, the other does.

like image 86
Martijn Pieters Avatar answered Sep 17 '22 23:09

Martijn Pieters