How to to create a multiline string in Python

Created
Modified

Using triple-quotes

String literals can span multiple lines. One way is using triple-quotes: """...""" or '''...'''. End of lines are automatically included in the string, but it’s possible to prevent this by adding a \ at the end of the line. The following example:

#!/usr/bin/env python3

str = """\
Usage: python [OPTIONS]
    -h        Display
    -H host   Hostname
"""
print(str)
Usage: python [OPTIONS]
    -h        Display
    -H host   Hostname

Using Brackets

List comprehensions provide a concise way to create lists. For example,

#!/usr/bin/env python3

sql = ("SELECT "
       "id, name "
       "FROM user")
print(sql)

# newline
sql = ("SELECT \n"
       "id, name \n"
       "FROM user")
print(sql)
SELECT id, name FROM user

SELECT 
id, name 
FROM user

Using Backslash

Adding a \ at the end of the line. For example,

#!/usr/bin/env python3

sql = "SELECT " \
    "id, name " \
    "FROM user"
print(sql)
SELECT id, name FROM user

Using join Method

The final approach is applying the string join() function to convert a string into multiline. For example,

#!/usr/bin/env python3

sql = ''.join("SELECT "
              "id, name "
              "FROM user")
print(sql)
SELECT id, name FROM user

Related Tags