Python Multiline String

Python Multiline String

In this article, we will see various ways of creating “Python Multiline Strings”. It will help you in implementing this concept and get a tight grip over this. 

Imagine you have a very long string that needs to be used in your program. Keeping all the text in a single line makes it difficult to read and looks clumsy. It gives better readability if you write it into multiple lines. Multiline String in python helps you to overcome this. 

Also, learn Strings in Python here.

Multiline String in Python:

Multiline String in Python

You can assign a multiline string to a variable in the following ways:

We have a long string as follows

1. By using three double quotes:

Python multiline string begins and ends with either three single quotes or three double-quotes.

Open the file editor and write the following

Example:

Save the program and run it. 

Output:

2. By using three single quotes:

Example:

Output:

Incase the String doesn’t have newline characters, we have to implement it in other ways to write in multiple lines. 

Note: Using three single quotes or three double quotes, the escape characters such as newline (\n), tab space (\t) become a part of the string.

3. Using Brackets

Using brackets we can split a string into multiple lines.

Example:

Output:

4. Using Backslash

Using backslash we can split a string into multiple lines in Python. In Python, backslash works as a line continuation character. We use it to join text which is separate lines. 

Example:

Output:

5. Multiline String creation using join()

Using string join() function, we can split a string into multiple lines. The advantage of using join() function in python over brackets or backslash way is there is no need to worry about the spaces or double spaces. 

Example:

Output:

Summary:

  • Python Multiline String gives better readability.
  • Three single quotes, three double quotes, brackets, and backslash can be used to create multiline strings. Whereas the user needs to mention the use of spaces between the strings.
  • If the multiline string in python is created using three single or three double quotes then the escape characters such as newline (\n), tab space (\t) become a part of the string.
  • String.join() function is also used to create multiline strings whereas there is no need to bother about spaces or double spaces between the strings.

Also Read:

Python Multiline String

Get our latest blog posts delivered to your inbox

Subscribe and get popular blog posts about software testing industry.

Rajkumar

Leave a Comment

Share via
Copy link
Powered by Social Snap