Triple Quotes in Python

PythonServer Side ProgrammingProgramming

Python's triple quotes comes to the rescue by allowing strings to span multiple lines, including verbatim NEWLINEs, TABs, and any other special characters.

The syntax for triple quotes consists of three consecutive single or double quotes.

Example

 Live Demo

#!/usr/bin/python
para_str = """this is a long string that is made up of several lines and non-printable characters such as TAB ( \t ) and they will show up that way when displayed. NEWLINEs within the string, whether explicitly given like this within the brackets [ \n ], or just a NEWLINE within the variable assignment will also show up.
"""
print para_str

Output

When the above code is executed, it produces the following result.

Note how every single special character has been converted to its printed form, right down to the last NEWLINE at the end of the string between the "up." and closing triple quotes. Also note that NEWLINEs occur either with an explicit carriage return at the end of a line or its escape code (\n) −

this is a long string that is made up of several lines and non-printable characters such as TAB ( ) and they will show up that way when displayed. NEWLINEs within the string, whether explicitly given like this within the brackets [ ], or just a NEWLINE within the variable assignment will also show up.

Raw strings do not treat the backslash as a special character at all. Every character you put into a raw string stays the way you wrote it −

Example

 Live Demo

#!/usr/bin/python
print 'C:\\nowhere'

Output

When the above code is executed, it produces the following result −

C:\nowhere

Now let's make use of raw string. We would put expression in r'expression' as follows −

Example

 Live Demo

#!/usr/bin/python
print r'C:\\nowhere'

Output

When the above code is executed, it produces the following result −

C:\\nowhere
raja
Published on 28-Jan-2020 12:22:40
Advertisements