Skip to Content
Course content

25: Multiline Strings and Docstrings

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I want to show you a mistake I see a lot when people start writing more complex scripts—specifically when they need to handle blocks of text like SQL queries, HTML templates, or long email bodies. Take a look at this snippet where someone is trying to build a basic database query:

def get_user_data(user_id):
    query = "SELECT username, email, join_date 
             FROM users 
             WHERE id = " + str(user_id)
    return query

print(get_user_data(101))

The EOL Scanning Error

If you try to run that, Python is going to throw a SyntaxError: EOL while scanning string literal. "EOL" stands for End of Line. Essentially, Python sees that opening double quote on the first line and starts looking for the closing quote. But it hits the end of the physical line before it finds one. Python doesn't just assume you wanted the string to continue on the next line; it assumes you forgot to close the quote and gives up.

Now, you could fix this by using concatenation or escape characters, but that makes your code look like a mess and is a pain to maintain. There's a much cleaner way.

Triple Quotes for Multiline Strings

In Python, we have triple quotes—either """ or '''. These tell Python, "Keep reading everything, including the line breaks, until you see another set of triple quotes." Let's fix that query:

def get_user_data(user_id):
    query = """SELECT username, email, join_date 
FROM users 
WHERE id = """ + str(user_id)
    return query

print(get_user_data(101))

This works perfectly. One thing to keep in mind: triple quotes preserve everything. If you indent the second and third lines of your string to make the code look pretty, those spaces and tabs actually become part of the string. I usually keep the multiline text flush against the left margin or use a helper function if the indentation is critical.

Turning Strings into Documentation

The exact same triple-quote syntax is used for something else entirely: Docstrings. A docstring is just a string literal that occurs as the first statement in a module, function, class, or method definition. Python doesn't just ignore these; it attaches them to the object as metadata.

I've worked on a few legacy projects where there were zero docstrings, and let me tell you—it's a nightmare. You spend half your day guessing what a function actually does. Here is how you should be doing it:

def calculate_compound_interest(principal, rate, time):
    """
    Calculates the total amount of an investment over time.
    
    Args:
        principal (float): The initial amount of money.
        rate (float): The annual interest rate (as a decimal).
        time (int): The number of years.
        
    Returns:
        float: The final balance.
    """
    return principal * (1 + rate) ** time

The magic here is that because this is a docstring, other developers (and your future self) can access this information without reading the source code. If you call help(calculate_compound_interest) in a Python console, Python will print out that exact block of text. It's the professional way to communicate how your code is intended to be used.




📋 Practical Task

Task: Building a Documented User Profile Generator

You need to create a function called generate_user_bio that takes three arguments: name, occupation, and hobby.

Your task is to:

  • Add a comprehensive docstring to the function explaining its purpose, its arguments, and what it returns.
  • Use a multiline string (triple quotes) to create a formatted biography template that looks like this:
Name: [name]
Job: [occupation]
Interest: [hobby]
--------------------
Status: Active

The function should return the completed biography string with the arguments inserted into the template. Test your function by calling it and printing the result to the console.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.