Python String Formatting and Variable Injection

This code example demonstrates Python programming techniques and best practices.

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)

Language: Python
Original Source: BlogEngine.NET Migration
Code Lines: 35

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.

 

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:

 

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:

 

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

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



Example 5: Using f-Strings for SQL Queries

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

 

Example 6: Safe SQL Queries with Parameterized Queries

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

 

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.

Python String Formatting and Variable Injection

Using Template Strings in Python Introduction to Template Strings in Python Template strings, or f-s