Python - Create String (Single, Double, Triple Quotes)

• Python offers three quoting styles—single, double, and triple quotes—each serving distinct purposes from basic strings to multiline text and embedded quotations

Key Insights

• Python offers three quoting styles—single, double, and triple quotes—each serving distinct purposes from basic strings to multiline text and embedded quotations • Single and double quotes are functionally identical for simple strings, but choosing the right one reduces escape character clutter when your string contains quotations • Triple quotes enable multiline strings and docstrings without concatenation or newline escapes, making them essential for documentation and formatted text blocks

Basic String Creation with Single and Double Quotes

Python treats single quotes (') and double quotes (") as interchangeable for creating strings. Both produce identical string objects with no performance difference.

# Single quotes
name = 'Alice'
message = 'Hello, World!'

# Double quotes
name = "Alice"
message = "Hello, World!"

# Both are equivalent
print('Alice' == "Alice")  # True
print(type('text'))        # <class 'str'>
print(type("text"))        # <class 'str'>

The choice between single and double quotes becomes meaningful when your string contains quotation marks. Using the opposite quote style eliminates the need for escape characters.

# Without escaping - clean and readable
single_with_double = "She said, 'Hello!'"
double_with_single = 'The book "1984" is dystopian.'

# With escaping - harder to read
single_escaped = 'She said, \'Hello!\''
double_escaped = "The book \"1984\" is dystopian."

# Both approaches work identically
print(single_with_double)  # She said, 'Hello!'
print(single_escaped)      # She said, 'Hello!'

Handling Apostrophes and Contractions

Apostrophes in contractions create a common scenario where quote choice matters. Double quotes provide cleaner syntax for strings containing apostrophes.

# Preferred - no escaping needed
message = "It's a beautiful day"
phrase = "Don't worry about it"
possessive = "Sarah's laptop"

# Works but requires escaping
message = 'It\'s a beautiful day'
phrase = 'Don\'t worry about it'
possessive = 'Sarah\'s laptop'

# Real-world example
user_input = "The user's profile shows they're active"
sql_fragment = "WHERE name = 'O''Reilly'"  # SQL requires doubled quotes

Triple Quotes for Multiline Strings

Triple quotes (''' or """) create multiline strings that preserve formatting, including newlines and indentation. This is Python’s cleanest approach for long text blocks.

# Triple single quotes
description = '''This is a long description
that spans multiple lines.
It preserves all formatting.'''

# Triple double quotes
sql_query = """
SELECT user_id, username, email
FROM users
WHERE active = true
  AND created_at > '2024-01-01'
ORDER BY username
"""

# The newlines are part of the string
print(repr(description))
# "This is a long description\nthat spans multiple lines.\nIt preserves all formatting."

Triple quotes handle embedded quotation marks without escaping:

mixed_quotes = """
He said, "It's important to understand Python's string types."
She replied, 'I agree completely!'
"""

json_template = '''
{
    "name": "John Doe",
    "message": "She said, 'Hello!'"
}
'''

Docstrings and Documentation

Triple double quotes (""") are the Python convention for docstrings—documentation strings that describe modules, classes, and functions.

def calculate_discount(price, percentage):
    """
    Calculate the discounted price.
    
    Args:
        price (float): Original price
        percentage (float): Discount percentage (0-100)
    
    Returns:
        float: Price after discount
    
    Example:
        >>> calculate_discount(100, 20)
        80.0
    """
    return price * (1 - percentage / 100)

class DataProcessor:
    """
    Process and transform data from various sources.
    
    This class provides methods for loading, cleaning,
    and exporting data in multiple formats.
    """
    
    def __init__(self, source):
        """Initialize with a data source path."""
        self.source = source

Access docstrings programmatically using the __doc__ attribute:

print(calculate_discount.__doc__)
print(DataProcessor.__doc__)

# Many tools use docstrings
help(calculate_discount)  # Displays formatted documentation

Escape Sequences and Raw Strings

All quote styles support escape sequences, but sometimes you want literal backslashes. Raw strings (prefix r) treat backslashes as literal characters.

# Regular strings interpret escape sequences
path = "C:\new\test"  # \n and \t are interpreted as newline and tab
print(path)           # C:
                      # ew    est

# Raw strings preserve backslashes
path = r"C:\new\test"
print(path)           # C:\new\test

# Useful for regex patterns
pattern = r"\d{3}-\d{2}-\d{4}"  # SSN pattern
regex_email = r"[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+"

# Windows file paths
file_path = r"C:\Users\Alice\Documents\report.pdf"

# Raw strings work with all quote styles
raw_single = r'C:\path\to\file'
raw_double = r"C:\path\to\file"
raw_triple = r"""C:\path\to\file"""

String Concatenation and Quote Mixing

Python automatically concatenates adjacent string literals, regardless of quote style. This improves readability for long strings.

# Implicit concatenation
message = "This is a long message " \
          "that spans multiple lines " \
          "using implicit concatenation."

# Mixed quote styles in concatenation
full_text = 'First part ' "second part " '''third part'''
print(full_text)  # First part second part third part

# Useful for breaking long strings
url = (
    "https://api.example.com/v1/"
    "users/12345/"
    "profile?include=posts,comments"
)

# Parentheses allow line breaks without backslashes
query = (
    "SELECT * FROM users "
    "WHERE status = 'active' "
    "AND role IN ('admin', 'moderator')"
)

Practical Examples and Best Practices

Choose quote styles based on string content and context:

# Configuration strings
config = {
    'database': "postgresql://localhost/mydb",
    'api_key': 'sk-proj-abc123',
    'message': "Welcome to the application!",
}

# HTML/XML templates - triple quotes for readability
html_template = """
<!DOCTYPE html>
<html>
    <head>
        <title>{title}</title>
    </head>
    <body>
        <h1>Welcome, {username}!</h1>
        <p>You have {count} new messages.</p>
    </body>
</html>
"""

# JSON strings - double quotes outside, single inside
json_data = '{"name": "Alice", "age": 30, "city": "NYC"}'

# Log messages with variables
log_entry = f"User '{username}' logged in at {timestamp}"

# Error messages
error_msg = "Invalid input: expected 'yes' or 'no'"

# Multi-paragraph text
terms = """
By using this service, you agree to our terms.

We reserve the right to modify these terms at any time.
Continued use constitutes acceptance of changes.
"""

String formatting with f-strings works with all quote styles:

name = "Alice"
age = 30

# All valid f-strings
info1 = f'Name: {name}, Age: {age}'
info2 = f"Name: {name}, Age: {age}"
info3 = f"""
Name: {name}
Age: {age}
"""

# Complex expressions
result = f"The user '{name}' is {age} years old and {'adult' if age >= 18 else 'minor'}"

Choose triple quotes for SQL queries, configuration files, and any text where preserving formatting matters. Use raw strings for regular expressions and file paths. For simple strings, prefer double quotes for consistency with JSON and most Python style guides, but switch to single quotes when the string contains double quotes to avoid escaping.

Liked this? There's more.

Every week: one practical technique, explained simply, with code you can use immediately.