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:


s="My Name is Pankaj.nI am the owner of JournalDev.comnJournalDev is a very popular website in Developers community."

We can write it using triple quotes as follows:


s = """My Name is Pankaj.
I am the owner of JournalDev.com
JournalDev is a very popular website in Developers community."""
Python Multiline String With Examples

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.


s = ("My Name is Pankaj. "
     "I am the owner of JournalDev.com and "
     "JournalDev is a very popular website in Developers community.")
print(s)

Output:


My Name is Pankaj. I am the owner of JournalDev.com and JournalDev is a very popular website in Developers community.
python-multiline-string-brackets

Multiline string using backslash


s = "My Name is Pankaj. "
    "I am the owner of JournalDev.com and "
    "JournalDev is a very popular website in Developers community."
print(s)
python-multiline-string-brackets

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.


s=" ".join(("My Name is Pankaj. I am the owner of",
              "JournalDev.com and",
              "JournalDev is a very popular website",
              "in Developers community."))
print(s)
python-multiline-string-join
You can checkout complete python script and more Python examples from our GitHub Repository.

By admin

Leave a Reply

%d bloggers like this: