C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Note: In this syntax, the Python interpreter scans for three quotes for the start and end of the literal. A single quote can also be used.
Note 2: We must surround a triple-quoted string with the same kind of quotes. Double quotes must be matched with double quotes.
Python program that uses triple-quotes
# Use a triple-quoted string.
v = """This string has
triple "quotes" on it."""
print(v)
Output
This string has
triple "quotes" on it.
Usually: It is best to use standard syntax like triple-quoted strings. Here we combine three string literals into one.
Python program that uses parentheses around literals
# Surround string literals with parentheses to combine them.
lines = ("cat "
"bird "
"frog")
print(lines)
Output
cat bird frog
Tip: Raw string literals are ideal for regular expression patterns. In "re" we often use the backslash.
Here: The "123" is treated as an escaped sequence in the normal string literal, but not in the raw one.
Paths: For file paths or folder paths, raw string literals are ideal. They eliminate confusion about slashes or backslashes on Windows.
PathPython program that uses raw string
# In a raw string "\" characters do not escape.
raw = r"\directory\123"
val = "\directory\123"
print(raw)
print(val)
Output
\directory\123
\directoryS
Python program that uses format literals
brick_color = "red"
brick_size = 50
# Use format literal.
result = f"the brick weighs {brick_size} and is {brick_color}"
print(result)
Output
the brick weighs 50 and is red
Caution: If you multiply a string against a large number, you may get a MemoryError. An if-check to prevent this may be helpful.
Python program that adds, multiplies strings
s = "abc?"
# Add two strings together.
add = s + s
print(add)
# Multiply a string.
product = s * 3
print(product)
Output
abc?abc?
abc?abc?abc?