In Python programs we often specify strings directly. This is a string
literal: a string
that is part of the program itself (in quotes).
For paths, particularly on Windows, we can use "r" to avoid having to escape path separators. And for newlines, we can use triple-quoted literals.
This literal syntax form begins and ends with three quotes. Newlines are left as is. In triple-quoted syntax, we do not need to escape quotes.
string
with the same kind of quotes. Double
quotes must be matched with double
quotes.# Use a triple-quoted string. v = """This string has triple "quotes" on it.""" print(v)This string has triple "quotes" on it.
We can place parentheses around string
literals on separate lines to combine them into one string
literal. This syntax is an alternative to triple-quoted in certain cases.
string
literals into one.# Surround string literals with parentheses to combine them. lines = ("cat " "bird " "frog") print(lines)cat bird frog
By prefixing a string
literal with an r, we specify a raw string
. In a raw string
, the backslash character does not specify an escape sequence—it is a regular character.
string
literals are ideal for regular expression patterns. In "re" we often use the backslash.string
literal, but not in the raw one.string
literals are ideal. They eliminate confusion about slashes or backslashes on Windows.# In a raw string "\" characters do not escape. raw = r"\directory\123" val = "\directory\123" print(raw) print(val)\directory\123 \directoryS
We can prefix a string
with the "f" character to specify a format literal. Variables in the current scope are placed inside the curly brackets surrounding their names.
brick_color = "red" brick_size = 50 # Use format literal. result = f"the brick weighs {brick_size} and is {brick_color}" print(result)the brick weighs 50 and is red
A string
can be added to another string
. And it can be multiplied by a number. This copies that same string
into a new string
the specified number of times.
string
against a large number, you may get a MemoryError
. An if
-check to prevent this may be helpful.s = "abc?" # Add two strings together. add = s + s print(add) # Multiply a string. product = s * 3 print(product)abc?abc? abc?abc?abc?
String
literals are everywhere in Python programs. For file paths, raw literals (with r) are an ideal syntax. We rarely multiply strings, but this too is possible.