Write a Python Program to Print Multi Line Strings

Python Programming offers multi-line strings in order to preserve the formatting of paragraphs,  and print the  paragraph on multiple lines exactly as  written by the  Python developer.

For example if you want to write a poem / paragraph / Quotes and you want to preserve the string formatting you can use multi line string

Let's look into simple programs

 

Write a Python Program to Print Multi Line Strings

 


Write a Python Program to Print Multi Line Strings

In order to use the Python multiline strings you should use double quotes three times and provide the required string inside the quotes. The setting should be enclosed with the ending quotes as shown below.  so you will be using six double quotes.


text = """this is a
multiline string.
containing 3 lines"""

print(text)



OUTPUT
==============

this is a
multiline string.
containing 3 lines





Instead of using double quotes you can also try  using the single quotes three times to start the multiline string and to end the string again and close it with the three single quotes. This will also preserve the formatting of multiline string

text = '''
this is a
multiline string.
containing 3 lines
'''

print(text)



OUTPUT
================

this is a
multiline string.
containing 3 lines





You can also use a single line string instead of multi line as shown below.

text = '''it’s a single line string'''
print(text)


OUTPUT
=================

it's a single line string





You cannot use double quotes with a single quotes it will throw a Syntax error

text = """it’s a line'''
print(text)


OUTPUT
=============
 File "C:/Users/Public/Projects/vlogs/main.py", line 9
    print(text)
              ^
SyntaxError: EOF while scanning triple-quoted string literal






Conclusion
=====================

You can use the multiline string enclosed using triple quotes  as shown above in order to preserve the formatting of the string.






Post a Comment

0 Comments