Related Articles

Related Articles

Triple quotes in Python
  • Last Updated : 29 Apr, 2020

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 Comments

filter_none

edit
close

play_arrow

link
brightness_4
code

"""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")

chevron_right


Output:

hello Geeks

Similarly, single triple quotes can also be used for the purpose as shown below:



filter_none

edit
close

play_arrow

link
brightness_4
code

'''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")

chevron_right


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:

filter_none

edit
close

play_arrow

link
brightness_4
code

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)

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

my_str = """I
am
a
Geek !"""
  
# check data type of my_str
print(type(my_str))
  
print(my_str)

chevron_right


Output:

<class 'str'>
I
am
a
Geek !

Example 3:
If we wish to ignore end of lines, we need to use ”

filter_none

edit
close

play_arrow

link
brightness_4
code

my_str = """I \
am \
a \
Geek !"""
  
# check data type of my_str
print(type(my_str))
  
print(my_str)

chevron_right


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.




My Personal Notes arrow_drop_up
Recommended Articles
Page :