In Python, triple quotes let us write strings that span multiple lines, using either three single quotes (''') or three double quotes ("""). While they’re most often used in docstrings (the text that explains how code works), they also have other features that can be used in a variety of situations Example:
s = """Line 1
Line 2
Line 3
"""
print(s)
Output
Line 1 Line 2 Line 3
Explanation: triple quotes let you write a string across multiple lines without using newline characters (\n).
Note: Triple quotes are docstrings or multi-line docstrings and are not considered comments according to official Python documentation.
Syntax of Triple Quotes
There are two valid ways to create a triple-quoted string:
Triple single quotes:
s = '''This is
a triple-quoted
string.'''
Triple double quotes:
s = """This is
also a triple-quoted
string."""
Triple Quotes for String creation
We can also declare strings in python using triple quote. Here's an example of how we can declare string in python using triple quote. Example:
s1 = '''I '''
s2 = """am a """
s3 = """Geek"""
# check data type of str1, str2 & str3
print(type(s1))
print(type(s2))
print(type(s3))
print(s1 + s2 + s3)
Output
<class 'str'> <class 'str'> <class 'str'> I am a Geek
Explanation: Even though the strings are declared with triple quotes, they behave exactly like normal strings. The + operator concatenates them.
Triple Quotes for Docstrings
Docstrings are string literals that appear as the first statement in a function, class, or module. These are used to explain what the code does and are enclosed in triple quotes. Example:
def msg(name):
"""Greets the person with the given name."""
print(f"Hello, {name}!")
s = "Anurag"
msg(s)
Output
Hello, Anurag!
Explanation: In this example, the string """Greets the person with the given name.""" is the docstring for the msg function.
Accessing Docstrings
Docstrings can be accessed using the __doc__ attribute or the built-in help() function.
def area(radius):
"""Calculates the area of a circle given its radius."""
import math
return math.pi * radius ** 2
print(area.__doc__)
help(area)
Output
Calculates the area of a circle given its radius.
Help on function area in module __main__:
area(radius)
Calculates the area of a circle given its radius.Explanation:
- area.__doc__ returns the docstring associated with the area() function.
- help() function displays the docstring along with the function signature.