triple-quoted string
In Python, a triple-quoted string is a string literal enclosed in a pair of triple quotes, either single (''') or double (""").
Triple-quoted strings can span multiple lines, making them useful for writing long strings, such as templates, docstrings, or string literals that contain line breaks. With triple-quoted strings, you don’t need to use escape characters for newlines, which can make your code more readable and maintainable.
You can also use triple-quoted strings to include both single and double quotes within the string without the need for escape characters. This feature comes in handy when you’re dealing with strings that contain complex text, such as HTML or JSON content, where quotes are common. The one exception is three unescaped quotes in a row matching the style that opened the literal, which ends the literal early. A triple-quoted string whose content ends with that same quote character still needs a backslash escape.
Example
Here’s a quick example of using a triple-quoted string in Python:
>>> triple_quoted = """This is a triple-quoted string.
... It can span multiple lines.
... You can include 'single' and "double" quotes without any issues."""
>>> print(triple_quoted)
This is a triple-quoted string.
It can span multiple lines.
You can include 'single' and "double" quotes without any issues.
In this example, you create a triple-quoted string using double quotes. This type of string literal can span multiple lines.
Related Resources
Tutorial
Strings and Character Data in Python
Work with Python strings using a rich set of operators and functions: string literals, the str() function, and the methods you'll use most.
For additional information on related topics, take a look at the following resources:
- Python String Formatting: Available Tools and Their Features (Tutorial)
- Write Python Docstrings Effectively (Course)
- Strings and Character Data in Python (Course)
- Python Strings and Character Data (Quiz)
- Python String Formatting Tips & Best Practices (Course)
- Python String Formatting: Available Tools and Their Features (Quiz)
Have a question about this? Mentor AI can show you examples, compare related terms, and point you to tutorials.