Detailed Explanation of Multi line Output of python String

  • 2021-11-10 09:50:29
  • OfStack

1. Use\ Continued line at the end of each line of the string

Write a string in multiple lines, with\ continuing at the end of each line. Note that the output is 1 line.


>>> string = ' No. 1 1 Row \
 …   No. 1 2 Row \
 …   No. 1 3 Row '
>>> print(string)
 'No. 1 Line number 2 Line number 3 Row '

2. Use 3 single quotation marks or 3 double quotation marks to represent a string

In Python, strings can also be represented by three single quotation marks or three double quotation marks, so that the contents of the string can be written and output on multiple lines.

With 3 quotation marks, strings can be written on multiple lines and output on multiple lines, without explicitly indicating\ n newlines.


>>> string =  ' ' 'No. 1 Row 
 …   No. 1 2 Row 
 …   No. 1 3 Row '''
>>> print(string)
 No. 1 1 Row 
 No. 1 2 Row 
 No. 1 3 Row 

Extension of knowledge points:

Python multiline string using join () (Python multiline string using join ())

We can also use the string join () function to break the string into multiple lines. Note that in square brackets or backslashes, we have to watch for spaces ourselves, and if the string is really long, checking spaces or doubling spaces can be a nightmare. We can eliminate it using the 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)

Related articles: