Spanning strings over multiple lines can be done using python’s triple quotes. It can also be used for long comments in code. Special characters like TABs, verbatim or NEWLINEs can also be used within the triple quotes. As the name suggests its syntax consists of three consecutive single or double-quotes.
Syntax: “”” string””” or ”’ string”’
Note: Triple quotes, according to official Python documentation are docstrings, or multi-line docstrings and are not considered comments. Anything inside triple quotes is read by the interpreter. When the interpreter encounters the hash symbol, it ignores everything after that. That is what a comment is defined to be.
Triple Quotes for Multi-Line Strings
Similarly, single triple quotes can also be used for the same purpose as shown below:
Note : We can also uses # in multiples lines, but triple quotes look much better.
Triple Quotes for String creation
Another use case of triple quotes is to create strings in Python. Adding the required characters within triple quotes can convert those characters into python strings. The below codes shows the use of triple quotes for creating strings:
Example 1:
Python3
str1 =
str2 =
str3 =
print ( type (str1))
print ( type (str2))
print ( type (str3))
print (str1 + str2 + str3)
|
Output<class 'str'>
<class 'str'>
<class 'str'>
I am a Geek
Example 2:
Multi-line strings using triple quotes. End of lines are included by default.
Python3
my_str =
print ( type (my_str))
print (my_str)
|
Output<class 'str'>
I
am
a
Geek !
Example 3:
If we wish to ignore end of lines, we need to use ” .
Python3
my_str =
print ( type (my_str))
print (my_str)
|
Output<class 'str'>
I am a Geek !