Of course! In Python, the concept of "addslashes" comes from PHP and other languages. Its primary purpose is to escape special characters in a string so that it can be safely used in contexts where those characters have a special meaning, such as in a database query or a shell command.

The most common and recommended way to achieve this in Python is by using the built-in json module, as it's more robust and standard than a simple manual replacement.
Here’s a complete guide covering the best methods and important considerations.
The Modern & Recommended Method: json.dumps()
For most use cases, especially when preparing data for databases, APIs, or configuration files, using json.dumps() is the best practice. It not only escapes quotes but also handles other special characters like newlines and control characters in a standardized way.
How it works: The json.dumps() function (dump string) serializes a Python object into a JSON formatted string. Part of this serialization process involves escaping characters to ensure the resulting string is valid JSON.

import json
my_string = 'This is a "test" string with a single quote: \' and a newline.\n'
# Use json.dumps() to escape the string
escaped_string = json.dumps(my_string)
print(f"Original: {my_string}")
print(f"Escaped: {escaped_string}")
Output:
Original: This is a "test" string with a single quote: ' and a newline.
Escaped: "This is a \"test\" string with a single quote: \' and a newline.\n"
Key Advantages:
- Comprehensive: Escapes all necessary characters (,
\, and control characters like\n,\t,\b, etc.). - Standard: JSON is a universal standard, making the output predictable and interoperable.
- Safe: Reduces the risk of injection vulnerabilities (like SQL injection) when used correctly.
The Manual str.replace() Method (For Simple Cases)
If you only need to escape a few specific characters and don't want the overhead of the json module, you can chain str.replace() calls. This mimics the behavior of the classic addslashes function more directly.
This method typically escapes:
- Single quote ()
- Double quote ()
- Backslash (
\)
my_string = "Let's escape this: \"hello\\world\""
# Chain replace() calls to escape the characters
# Order matters: escape backslash first!
escaped_string = my_string.replace('\\', '\\\\') \
.replace('"', '\\"') \
.replace("'", "\\'")
print(f"Original: {my_string}")
print(f"Escaped: {escaped_string}")
Output:
Original: Let's escape this: "hello\world"
Escaped: Let\'s escape this: \"hello\\world\"
⚠️ Important Caveat: This simple method does not handle other control characters like newlines (\n) or tabs (\t). For most applications, this is insufficient and potentially unsafe.
When NOT to Use addslashes: SQL Injection
A very common mistake is to try to use addslashes to prevent SQL injection. You should never do this.
The correct and safe way to handle database queries is by using parameterized queries (also prepared statements). Your database driver provides this functionality.
The WRONG Way (Vulnerable to SQL Injection)
import sqlite3 # DANGEROUS: DO NOT DO THIS user_id = "1 OR 1=1" query = "SELECT * FROM users WHERE id = " + addslashes(user_id) # Or manual replace # An attacker could provide user_id = "1; DROP TABLE users; --" # The query would become: SELECT * FROM users WHERE id = 1; DROP TABLE users; -- # This could destroy your database!
The RIGHT Way (Using Parameterized Queries)
import sqlite3
import json # Using json.dumps for the value is still a good practice
# The value comes from an untrusted source (e.g., user input)
user_id = "1 OR 1=1"
# The '?' is a placeholder. The driver safely handles the value.
query = "SELECT * FROM users WHERE id = ?"
# Connect to the database
conn = sqlite3.connect('example.db')
cursor = conn.cursor()
# Execute the query with the value as a separate argument
# The driver ensures the value is treated as data, not as part of the SQL command.
cursor.execute(query, (user_id,))
results = cursor.fetchall()
print(results) # This will safely return no results, as the string "1 OR 1=1" is not a valid ID.
conn.close()
Summary: Which Method to Use?
| Use Case | Recommended Method | Why? |
|---|---|---|
| General Purpose Escaping | json.dumps(my_string) |
Best practice. Robust, standardized, and handles all necessary characters. Safe for databases, APIs, and config files. |
| Simple String Manipulation | my_string.replace(...).replace(...) |
Quick and easy for very simple needs where you only care about quotes and backslashes and don't need full JSON compliance. |
| Preventing SQL Injection | Parameterized Queries (cursor.execute("... WHERE id = ?", (value,))) |
The only correct and safe way. Never use string manipulation or addslashes for this. It protects against all SQL injection vectors. |
| Shell Command Injection | shlex.quote() |
The correct tool for escaping strings that will be passed as arguments to a shell command. |
Custom addslashes Function (For Legacy Code)
If you absolutely need a function that behaves exactly like the PHP addslashes (for porting old code, for example), you can easily create one.
def addslashes(string):
"""
Escapes single quotes, double quotes, and backslashes.
This mimics the behavior of the PHP addslashes function.
WARNING: This is NOT sufficient for preventing SQL injection.
Use parameterized queries for that.
"""
return string.replace('\\', '\\\\').replace('"', '\\"').replace("'", "\\'")
# Example usage
my_string = "O'Reilly said, \"Python is great!\""
escaped = addslashes(my_string)
print(f"Original: {my_string}")
print(f"Escaped: {escaped}")
Output:
Original: O'Reilly said, "Python is great!"
Escaped: O\'Reilly said, \"Python is great!\" 