Skip to content
Related Articles

Related Articles

Improve Article

Triple quotes in Python

  • Last Updated : 30 Jun, 2021

Spanning strings over multiple lines can be done using python’s triple quotes. It is also 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”’

 

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")
Output: 
hello Geeks

 

Similarly, single triple quotes can also be used for the 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 comments using double triple-quotes'''
 
print("hello Geeks")
Output: 
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)
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 = """I
am
a
Geek !"""
 
# check data type of 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 = """I \
am \
a \
Geek !"""
 
# check data type of my_str
print(type(my_str))
 
print(my_str)
Output: 
<class 'str'>
I am a Geek !

 

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course




My Personal Notes arrow_drop_up
Recommended Articles
Page :