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¶
>>> print('first line\nsecond line')
first line
second line
More (but not all) escape sequences …
Escape character |
Meaning |
---|---|
|
Linefeed |
|
Carriage return |
|
Tab |
|
Backspace |
|
ASCII 0 |
|
ASCII dec. 88 (‘X’) in octal |
|
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
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¶
>>> 'Hello' ' ' 'World'
'Hello World'
>>> ('Hello'
... ' '
... 'World')
'Hello World'