String Special Cases#
Note
Source: Escape sequences table drawn directly from the SE4ML Python
chapter (chapter_python.rst, lines 2356–2413). Raw strings, multiline
strings, and the in operator section are adapted from the SE4ML
presentation.
Escape Sequences#
Some characters cannot be typed directly inside a string literal. Python uses escape sequences — a backslash followed by a character — to represent them:
Sequence |
Meaning |
|---|---|
|
Literal backslash |
|
Single quote |
|
Double quote |
|
Newline (line feed) |
|
Tab |
|
Carriage return |
|
Null character |
>>> print("Line one\nLine two")
Line one
Line two
>>> print("Column 1\tColumn 2")
Column 1 Column 2
>>> print("She said, \"Hello.\"")
She said, "Hello."
Raw Strings#
If you need a string that contains many backslashes — such as a Windows file
path — a raw string treats backslashes as literal characters. Prefix the
opening quote with r:
>>> path = r"C:\Users\student\Documents"
>>> print(path)
C:\Users\student\Documents
Without the r, \U, \s, and \D would be interpreted as escape
sequences (and either produce unexpected characters or errors).
Multiline Strings#
Triple-quoted strings can span multiple lines and preserve all whitespace, including newlines:
message = """Dear student,
Welcome to Introduction to Computer Science.
Regards,
The Department"""
print(message)
Output:
Dear student,
Welcome to Introduction to Computer Science.
Regards,
The Department
Triple-quoted strings are also used as docstrings — documentation attached to functions and classes. We will see those in the Functions chapter.
Testing for Substrings#
The in operator tests whether one string is a substring of another:
>>> "cat" in "concatenate"
True
>>> "dog" in "concatenate"
False
>>> "not" not in "certainly"
True