Multiline Strings
Multiline strings in Python are strings that span multiple lines. They are useful for representing large blocks of text, such as documentation, long strings, or text that includes line breaks. Python provides several ways to handle multiline strings, each with its own use cases.
Using Triple Quotes
Multiline strings are typically created using triple quotes. Python supports both triple single quotes (”’) and triple double quotes (“””).
Triple Single Quotes
# Multiline string with triple single quotes multiline_string = '''This is a string that spans multiple lines. It preserves line breaks and spaces.''' print(multiline_string)
Triple Double Quotes
# Multiline string with triple double quotes multiline_string = """This is a string that spans multiple lines. It preserves line breaks and spaces.""" print(multiline_string)
Both methods will yield the same result, and you can choose based on personal preference or readability.
Preserving Line Breaks and Spaces
When using triple quotes, Python preserves line breaks and spaces exactly as they appear in the string literal.
# Multiline string with preserved line breaks and spaces multiline_string = """Line 1 Line 2 with extra spaces Line 3""" print(multiline_string) Output: mathematica Copier le code Line 1 Line 2 with extra spaces Line 3
Concatenating Multiline Strings
You can concatenate multiline strings in Python using implicit concatenation or by using the + operator.
Implicit Concatenation
Python allows implicit concatenation of strings that are placed next to each other.
# Implicit concatenation of multiline strings multiline_string = ( "This is the first part of the string.\n" "This is the second part of the string." ) print(multiline_string)
Using the + Operator
# Concatenation using the + operator part1 = """This is the first part of the string.""" part2 = """This is the second part of the string.""" multiline_string = part1 + "\n" + part2 print(multiline_string)
Removing Leading and Trailing Whitespace
Multiline strings often contain leading or trailing whitespace. To handle this, you can use the strip(), lstrip(), or rstrip() methods to remove unwanted whitespace.
Removing Leading and Trailing Whitespace
# Removing leading and trailing whitespace multiline_string = """ This is a string with leading and trailing whitespace. """ clean_string = multiline_string.strip() print(f"'{clean_string}'")
Removing Leading Whitespace Only
# Removing leading whitespace only multiline_string = """ This is a string with leading whitespace. """ clean_string = multiline_string.lstrip() print(f"'{clean_string}'")
Removing Trailing Whitespace Only
Formatting Multiline Strings
For better readability and formatting, you can use multiline strings with embedded expressions using f-strings or the format() method.
Using f-strings (Python 3.6+)
name = "Alice" age = 30 formatted_string = f"""Name: {name} Age: {age} """ print(formatted_string)
Using format() Method
name = "Alice" age = 30 formatted_string = """Name: {} Age: {} """.format(name, age) print(formatted_string)
Using Multiline Strings in Documentation
Multiline strings are often used for docstrings to provide documentation for modules, classes, and functions.
Module Docstring
"""This module performs various string operations. It includes functions for string manipulation and formatting."""
Function Docstring
def greet(name): """Greets the user with their name. Args: name (str): The name of the user. Returns: str: A greeting message. """ return f"Hello, {name}!"
Example Use Cases
Writing Multi-line Text to a File
You can use multiline strings to write large blocks of text to a file.
# Writing a multiline string to a file with open('example.txt', 'w') as file: file.write("""This is a multiline string that will be written to a file. It spans multiple lines.""") # Reading the file content with open('example.txt', 'r') as file: content = file.read() print(content)
Including Long SQL Queries
Multiline strings are useful for writing long SQL queries.
# Long SQL query using a multiline string sql_query = """ SELECT id, name, age FROM users WHERE age > 21 ORDER BY name; """ print(sql_query)