Python Multiline String With Examples

Sometimes we have a very long string and we want to write it into multiple lines for better code readability. Python provides various ways to create multiline strings.

Python Multiline String using triple quotes

If your long string has newline characters, then you can use triple quotes to write them into multiple lines. Note that anything goes inside triple quotes is the string value, so if your long string has many newline characters then you can use it to split them into multiple lines.

Let’s say we have a long string as follows:

We can write it using triple quotes as follows:

But what if the string doesn’t have newline characters, then there are other ways to write them in multiple lines.

Multiline string using brackets

We can split a string into multiple lines using brackets.


Multiline string using backslash

Python multiline string using join()

We can also split a string into multiple lines using string join() function. Note that in brackets or backslash way, we have to take care of spaces yourself and if the string is really long then it can be a nightmare to check for spaces or double spaces. We can get rid of that using join() function as shown below.

You can checkout complete python script and more Python examples from our GitHub Repository.

By admin

Leave a Reply