You are currently viewing Python Create a long Multi-line String

How to create a long multi-line string in Python? In Python, a Multi-line string allows you to create a string that spans multiple lines without having to use the newline character between each line. To create a multi-line string, use 3 single or double quotes around the text.

Advertisements

We are often required to create a long string that spans multiple lines of code. In this article, we will discuss what multi-line strings are and how to create them using both triple quotes and escape characters in Python.

1. What is a Multi-line String

In Python, a string is a sequence of characters. A multi-line string is a string that spans across multiple lines of code. Multi-line strings can be created using either triple quotes or escape characters. Triple quotes are either single quotes (''') or double quotes (""") that allow you to create a string that spans multiple lines without having to use the newline character (\n) between each line.

Below is an example of a multi-line string created using triple quotes:


# Create multi-line string
multi_line_string = '''
This is a
multi-line string
created using
triple quotes.
'''

This yields the below output.

Many programming languages, including Java, C++, Ruby, and Perl, support multi-line strings in some form or another. The syntax for creating multi-line strings may vary from language to language.

In Python, you can create a multi-line string using either triple quotes or escape characters, which is a syntax unique to the language.

2. Multi-line String with Triple Quotes

Triple quotes are a convenient way to create multi-line strings in Python. When using triple quotes, you can create a string that spans multiple lines without having to use the newline character (\n) between each line. Triple quotes can be either single quotes (''') or double quotes (""").


# Create multi-line string using triple quotes
multi_line_string = '''
This is a
multi-line string
created using
triple quotes.
'''

print(mutli_line_string)

Yields, the following output:

python create multi-line string

We can also use 3 double quotes instead of single quotes. See the following example:


# Multi line string using double quotes
multi_line_string = """
This is a 
multi-line string 
created using 
triple quotes and a 
backslash continuation character.
"""

print(multi_line_string)

You can use double quotes, or single quotes, inside the triple quotes. It will be a part of the output text. See the below examples.


# Using quotes in multi-line string
multi_line_string = """
Using 
"dobule quotoes"
inside tripple quotes
"""

print(multi_line_string)

Yields, the following output:

3. Multi-line String with Escape Characters

You can also create multi-line strings in Python using escape characters. Escape characters are special characters that are used to represent other characters that can’t be directly typed into a string.

One of the most commonly used escape characters is the newline character (\n), which is used to create a new line in a string.


# Multi-line string with escape characters
multi_line_string = "This is a\nmulti-line string\nin python."
print(multi_line_string)

Yields the following 3 lines of text:


This is a
multi-line string
in python.
  1. Escape characters may be necessary when working with programming languages or tools that don’t support triple quotes.
  2. Escape characters can be used when creating a string that contains triple quotes.
  3. Escape characters can be useful when you need to create a string with a specific format or layout.

4. Use cases for multi-line strings in Python

Multi-line strings are commonly used for documentation strings (docstrings), SQL queries, HTML templates, and other cases where you need to create multi-line strings. Let’s see some of them below:

4.1 Documentation Strings (docstrings)

Docstrings are used to provide information about the purpose of the code, how it should be used, and any arguments or return values.

Docstrings are defined using multi-line strings enclosed in triple quotes, and they are placed immediately after the module, class, function, or method definition.


def square(n):
    """
    This function takes a number as input and returns its square.

    Parameters:
    n (int or float): The number to square.

    Returns:
    int or float: The square of the input number.
    """
    return n**2

Now when you use the Python help() function to get information about the square function, the docstring will be displayed:


>>> help(square)
Help on function square in module __main__:

square(n)
    This function takes a number as input and returns its square.

    Parameters:
    n (int or float): The number to square.

    Returns:
    int or float: The square of the input number.

4.2 SQL Queries

In Python, SQL queries are often executed using libraries like SQLAlchemy or pyodbc. To create SQL queries in Python, you can use multi-line strings enclosed in triple quotes.

Multi-line strings make it easy to write complex SQL queries that span multiple lines and to include variables and other dynamic content in your queries.

See the following example of SQL query with a multi-line string:


import sqlite3

# Connect to a SQLite database
conn = sqlite3.connect('mydatabase.db')

# Define a SQL query to select data from a table
query = '''
SELECT *
FROM my_table
WHERE my_column = ?
'''

# Execute the query and get the results
cursor = conn.cursor()
cursor.execute(query, ('some_value',))
result = cursor.fetchall()
for row in result:
    print(row)

# Close the database connection
conn.close()

4.3 HTML templates

You can use multi-line strings enclosed in triple quotes to define HTML templates. Multi-line strings make it easy to create HTML templates that span multiple lines and contain dynamic content.

See the below example of an HTML template with a multi-line string:


# Define an HTML template
html_template = '''
<!DOCTYPE html>
<html>
    <head>
        <title>{title}</title>
    </head>
    <body>
        <h1>{header}</h1>
        <p>{body}</p>
    </body>
</html>
'''

# Define variables to substitute into the template
title = 'My Website'
header = 'Welcome to My Website'
body = 'This is the body of my website.'

# Substitute variables into the template
html = html_template.format(title=title, header=header, body=body)

# Print the resulting HTML
print(html)

Yields the below output:


<!DOCTYPE html>
<html>
    <head>
        <title>My Website</title>
    </head>
    <body>
        <h1>Welcome to My Website</h1>
        <p>This is the body of my website.</p>
    </body>
</html>

5. Summary and Conclusion

Multi-line strings are an important tool in Python for working with long strings of text. By using triple quotes or escape characters, you can easily create multi-line strings that span multiple lines and contain dynamic content. We can work with documentation strings, SQL queries, HTML templates, and more. If you have any questions, please leave them in the comment section.

Happy Coding!

Related Articles