PYTHON addslashes

is this article helpful?
|
Python replacement for PHP's addslashes [ edit | history ]
Note: this function does not exist in Python because since 1996 Python has a standard Database API http://www.python.org/dev/peps/pep-0249/ and the DBAPI has an execute method which safely and automatically escapes parameters to be inserted into the SQL query string, making something like addslashes unnecessary. If you think you need addslashes to build queries in Python, you are probably making queries in a suboptimal and possibly unsafe way.

def addslashes(s):
    d = {'"':'\\"', "'":"\\'", "\0":"\\\0", "\\":"\\\\"}
    return ''.join(d.get(c, c) for c in s)

s = "John 'Johny' Doe (a.k.a. \"Super Joe\")\\\0"
print s
print addslashes(s)
#John 'Johny' Doe (a.k.a. "Super Joe")\
#John \'Johny\' Doe (a.k.a. \"Super Joe\")\\\



I think there may be an more efficient but uglier way to do it as the following:
def addslashes(s):
    l = ["\\", '"', "'", "\0", ]
    for i in l:
        if i in s:
            s = s.replace(i, '\\'+i)
    return s


Processing Comparison

import time
s = "John 'Johny' Doe (a.k.a. \"Super Joe\")\\\0" * 1000
def addslashes(s):
    t1 = time.time()
    d = {'"':'\\"', "'":"\\'", "\0":"\\\0", "\\":"\\\\"}
    s = ''.join(d.get(c, c) for c in s)
    print time.time() - t1

def addslashes1(s):
    t1 = time.time()
    l = ["\\", '"', "'", "\0", ]
    for i in l:
        if i in s:
            s = s.replace(i, '\\'+i)
    print time.time() - t1

addslashes(s)
0.158378839493
addslashes1(s)
0.000412940979004

PHP addslashes

PHP original manual for addslashes [ show | php.net ]

addslashes

(PHP 4, PHP 5)

addslashesQuote string with slashes

Description

string addslashes ( string $str )

Returns a string with backslashes before characters that need to be quoted in database queries etc. These characters are single quote ('), double quote ("), backslash (\) and NUL (the NULL byte).

An example use of addslashes() is when you're entering data into a database. For example, to insert the name O'reilly into a database, you will need to escape it. Most databases do this with a \ which would mean O\'reilly. This would only be to get the data into the database, the extra \ will not be inserted. Having the PHP directive magic_quotes_sybase set to on will mean ' is instead escaped with another '.

The PHP directive magic_quotes_gpc is on by default, and it essentially runs addslashes() on all GET, POST, and COOKIE data. Do not use addslashes() on strings that have already been escaped with magic_quotes_gpc as you'll then do double escaping. The function get_magic_quotes_gpc() may come in handy for checking this.

Parameters

str

The string to be escaped.

Return Values

Returns the escaped string.

Examples

Example #1 An addslashes() example

<?php
$str 
"Is your name O'reilly?";

// Outputs: Is your name O\'reilly?
echo addslashes($str);
?>

See Also