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
Python3
"""This is a really long comment that can make the code look ugly and uncomfortable to read on a small screen so it needs to be broken into multi-line strings using double triple-quotes""" print ( "hello Geeks" ) |
hello Geeks
Similarly, single triple quotes can also be used for the same purpose as shown below:
Python3
'''This is a really long comment that can make the code look ugly and uncomfortable to read on a small screen so it needs to be broken into multi-line strings using double triple-quotes''' print ( "hello Geeks" ) |
hello Geeks
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 = """I """ str2 = """am a """ str3 = """Geek""" # check data type of str1, str2 & str3 print ( type (str1)) print ( type (str2)) print ( type (str3)) print (str1 + str2 + str3) |
<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 = """I am a Geek !""" # check data type of my_str print ( type (my_str)) print (my_str) |
<class 'str'> I am a Geek !
Example 3:
If we wish to ignore end of lines, we need to use ” .
Python3
my_str = """I \ am \ a \ Geek !""" # check data type of my_str print ( type (my_str)) print (my_str) |
<class 'str'> I am a Geek !