More About Strings

String Delimiters

Delimiters: double quotes (“…”) or single quotes (‘…’), as needed

>>> 'spam eggs'  # single quotes
'spam eggs'
>>> 'doesn\'t'  # use \' to escape the single quote...
"doesn't"
>>> "doesn't"  # ...or use double quotes instead
"doesn't"
>>> '"Yes," he said.'
'"Yes," he said.'
>>> "\"Yes,\" he said."
'"Yes," he said.'
>>> '"Isn\'t," she said.'
'"Isn\'t," she said.'

Escape Sequences

Newline, embedded in string
>>> print('first line\nsecond line')
first line
second line

More (but not all) escape sequences

Escape character

Meaning

\n

Linefeed

\r

Carriage return

\t

Tab

\b

Backspace

\0

ASCII 0

\130

ASCII dec. 88 (‘X’) in octal

\x58

ASCII dec. 88 (‘X’) in hexadecimal

Raw Strings

Unwanted escaping (Doze pathnames)

>>> print('C:\some\name')
C:\some
ame
>>> print(r'C:\some\name')
C:\some\name
Unwanted escaping (regular expressions)
regex = re.compile(r'^(.*)\.(\d+)$')

Multiline Strings

Escaping newlines is no fun

print("""\
Bummer!
You messed it up!
""")

will produce …

Bummer!
You messed it up!
  • Note how the initial newline is escaped ⟶ line continuation

  • Newline must immediately follow backslash

More String Tricks

String literal concatenation
>>> 'Hello' ' ' 'World'
'Hello World'
String literal concatenation (multiple lines)
>>> ('Hello'
... ' '
... 'World')
'Hello World'