A union of curiosity and data science

Knowledgebase and brain dump of a database engineer


Python String Formatting and Variable Injection

Using Template Strings in Python

Introduction to Template Strings in Python

Template strings, or f-strings, allow you to embed expressions inside string literals using curly braces {}. They are especially useful for creating strings that include values of variables or expressions. Here’s how to use template strings, handle multiline text, and safely create SQL queries in Python.

Example 1: Multiline f-String

You can create a multiline f-string using triple quotes. This allows you to include line breaks directly in your string.

name = "Alice"
age = 30
occupation = "Engineer"

# Multiline f-string using triple quotes
multiline_string = f"""
Hello, my name is {name}.
I am {age} years old.
I work as an {occupation}.
"""

print(multiline_string)
 

Example 2: Using str.format() for Placeholders

If you want to leave placeholders in a string and pass the values later, you can use the str.format() method:

# Define a string with placeholders
template_string = """
Hello, my name is {name}.
I am {age} years old.
I work as a {occupation}.
"""

# Pass in the values for the placeholders
filled_string = template_string.format(name="Alice", age=30, occupation="Engineer")

print(filled_string)
 

Example 3: Using Template from the string Module

You can also use the Template class from the string module for a more traditional templating mechanism:

from string import Template

# Define a template string with placeholders using $ notation
template_string = Template("""
Hello, my name is $name.
I am $age years old.
I work as an $occupation.
""")

# Substitute the placeholders with actual values
filled_string = template_string.substitute(name="Alice", age=30, occupation="Engineer")

print(filled_string)
 

Example 4: Correct Usage with str.format() in SQL Queries

To use str.format() with SQL queries, replace placeholders with curly braces:

title = "Software Engineer"
field = "Software Development"

# Use curly braces {} as placeholders
query = "SELECT 1 FROM agent_role WHERE field = '{}' AND title = '{}'".format(field, title)

print(query)
    


Example 5: Using f-Strings for SQL Queries

Alternatively, you can use f-strings for the same purpose:

title = "Software Engineer"
field = "Software Development"

# Use f-string for formatting
query = f"SELECT 1 FROM agent_role WHERE field = '{field}' AND title = '{title}'"

print(query)
 

Example 6: Safe SQL Queries with Parameterized Queries

To avoid SQL injection risks, use parameterized queries with libraries like sqlite3:

import sqlite3

title = "Software Engineer"
field = "Software Development"

# Connect to your database
conn = sqlite3.connect('example.db')

# Use a parameterized query with ?
cursor = conn.execute("SELECT 1 FROM agent_role WHERE field = ? AND title = ?", (field, title))

# Fetch results
results = cursor.fetchall()
print(results)

# Close the connection
conn.close()
 

Conclusion

Using template strings in Python, whether with f-strings, str.format(), or the Template class, provides a flexible way to create dynamic strings. When handling SQL queries, always use parameterized queries to ensure security against SQL injection attacks.

Add comment