How to Selectively Escape Percent (%) in Python Strings

How can I selectively escape percent (%) in Python strings?

>>> test = "have it break."
>>> selectiveEscape = "Print percent %% in sentence and not %s" % test
>>> print selectiveEscape
Print percent % in sentence and not have it break.

Escape characters when joining strings

You need to add \ to your path when concatenating:

read_this_file = '\\folder1\\folder2\\' + max(filename_list)

But a better way to avoid that problem is to use

os.path.join("\\folder1\\folder2", max(filename_list))

str.contain \ should only be used as an escape character outside of raw strings

There is a difference between escaping the characters in python to be interpreted as a special character (e.g. \n is a newline and has nothing to do with n), and escaping the character not to be interpreted as a special symbol in the regex. Here you need both.

Either use a raw string:

mask = df['column'].str.contains(r'\+')

or escape the backslash:

mask = df['column'].str.contains('\\+')

Example:

df = pd.DataFrame({'column': ['abc', 'ab+c']})

df['column'].str.contains(r'\+')

0 False
1 True
Name: column, dtype: bool

How to use variables in SQL statement in Python?

cursor.execute("INSERT INTO table VALUES (%s, %s, %s)", (var1, var2, var3))

Note that the parameters are passed as a tuple.

The database API does proper escaping and quoting of variables. Be careful not to use the string formatting operator (%), because

  1. it does not do any escaping or quoting.
  2. it is prone to Uncontrolled string format attacks e.g. SQL injection.


Related Topics



Leave a reply



Submit