Multiline strings and newlines

If you want a literal string containing newlines, you have two options:

  • Use multiline strings,
  • Use escape sequences.   

First, let's look at multiline strings. Multiline strings are delimited by three quote characters rather than one. Here's an example using three double-quotes:

>>> """This is
... a multiline
... string"""
'This is a multiline string'

Notice how, when the string is echoed back to us, the newlines are represented by the escape sequence.

We can also use three single-quotes:

>>> '''So
... is
... this.'''
'So is this.'

As an alternative to using multiline quoting, we can just embed the control characters ourselves:

>>> m = 'This string
spans mutiple
lines'
>>> m
'This string spans mutiple lines'

To get a better sense of what we're representing in this case, we can use the built-in print() function to see the string:

>>> print(m)
This string
spans mutiple
lines

If you're working on Windows, you might be thinking that newlines should be represented by the carriage-return, newline couplet rather than just the newline character, . There's no need to do that with Python, since Python 3 has a feature called universal newline support which translates from the simple to the native newline sequence for your platform on input and output. You can read more about Universal Newline Support in PEP 278.

We can use the escape sequences for other purposes, too, such as incorporating tabs with or using quote characters inside strings with :

>>> "This is a " in a string"
'This is a " in a string'

The other way around:

>>> 'This is a ' in a string'
"This is a ' in a string"

As you can see, Python is smarter than we are at using the most convenient quote delimiters, although Python will also resort to escape sequences when we use both types of quotes in a string:

>>> 'This is a " and a ' in a string'
'This is a " and a ' in a string'

Because the backslash has special meaning, to place a backslash in a string we must escape the backslash with itself:

>>> k = 'A \ in a string'
'A \ in a string'

To reassure ourselves that there really is only one backslash in that string, we can print() it:

>>> print(k)
A in a string

You can read more about escape sequences in the Python documentation.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset