Multiline string in Python

In this tutorial, we will learn multiline string in Python. When there is not only a single line but more than one line. So, it becomes very difficult for readers to get it i.e. it kills readability of the text so, to avoid this problem we use multiline strings in Python. So, it had been explained below with various examples which will clear all your doubts and also increase your knowledge regarding Python language.

There are various ways to write multiline strings in Python. The main way is by putting triple quotes whether it’s three single quotes or three double-quotes. Even the indentation rule for blocks is not applied for the multiline strings so, it’s way simpler to add any text in the way that the programmer wants.

Alternatively, we can also use brackets for multiline strings i.e. to spread text in multiple different lines as required. String join() function can also be used for this purpose. Remember single backslash in Python is used for continuing the text i.e. it works as a continuation character.

Let’s see some examples…

Using Triple Quotes: Multiline string in Python

CODE:-

n="I'm learning Python basics. \n I use to prefer codespeedy.com for it. \n I'm loving it."
print("Normal string :- ",n)

m="""I'm learning Python basics.
I use to prefer codespeedy.com for it. 
I'm loving it."""
print("Multiple string :- ",m)

m='''I'm learning Python basics.
I use to prefer codespeedy.com for it.
I'm loving it.'''
print("Multiple string :- ",m)

m=""" I'm learning Python basics.\n
I use to prefer codespeedy.com for it.\n
I'm loving it."""
print("\nMultiple string :- ",m)

OUTPUT:-

Normal string :- I'm learning Python basics.
I use to prefer codespeedy.com for it.
I'm loving it.
Multiple string :- I'm learning Python basics.
I use to prefer codespeedy.com for it.
I'm loving it.
Multiple string :- I'm learning Python basics.
I use to prefer codespeedy.com for it.
I'm loving it.

Multiple string :- I'm learning Python basics.

I use to prefer codespeedy.com for it.

I'm loving it.

Using Brackets: Multiline string

CODE:-

m=("I'm learning Python basics.\n" "I use to prefer codespeedy.com for it.\n" "I'm loving it.")
print(m)

OUTPUT:-

I'm learning Python basics.
I use to prefer codespeedy.com for it.
I'm loving it.

Using join() function

CODE:-

m=' '.join(("I'm learning Python basics.\n" ,"I use to prefer codespeedy.com for it.\n" ,"I'm loving it."))
print(m)

OUTPUT:-

I'm learning Python basics.
I use to prefer codespeedy.com for it.
I'm loving it.

Also learn:

Leave a Reply

Your email address will not be published.