Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Effective replacing of substring

I have code like this:

def escape_query(query):
    special_chars = ['\\','+','-','&&','||','!','(',')','{','}','[',']',
                     '^','"','~','*','?',':']
    for character in special_chars:
        query = query.replace(character, '\\%s' % character)
    return query

This function should escape all occurrences of every substring (Notice && and ||) in special_characters with backslash.

I think, that my approach is pretty ugly and I couldn't stop wondering if there aren't any better ways to do this. Answers should be limited to standart library.

like image 987
nagisa Avatar asked Dec 30 '25 18:12

nagisa


2 Answers

Using reduce:

def escape_query(query):
  special_chars =  ['\\','+','-','&&','||','!','(',')','{','}','[',']',
                     '^','"','~','*','?',':']
  return reduce(lambda q, c: q.replace(c, '\\%s' % c), special_chars, query)
like image 155
Ismail Badawi Avatar answered Jan 02 '26 06:01

Ismail Badawi


The following code has exactly the same principle than the steveha's one.
But I think it fulfills your requirement of clarity and maintainability since the special chars are still listed in the same list as yours.

special_chars = ['\\','+','-','&&','||','!','(',')','{','}','[',']',
                 '^','"','~','*','?',':']

escaped_special_chars = map(re.escape, special_chars)

special_chars_pattern = '|'.join(escaped_special_chars).join('()')

def escape_query(query, reg = re.compile(special_chars_pattern) ):
    return reg.sub(r'\\\1',query)

With this code:
when the function definition is executed, an object is created with a value (the regex re.compile(special_chars_pattern) ) received as default argument, and the name reg is assigned to this object and defined as a parameter for the function.
This happens only one time, at the moment when the function definition is executed, which is performed only one time at compilation time.
That means that during the execution of the compiled code that takes place after the compilation, each time a call to the function will be done, this creation and assignement won't be done again: the regex object already exists and is permanantly registered and avalaible in the tuple func_defaults that is definitive attribute of the function.
That's interesting if several calls to the function are done during execution, because Python has not to search for the regex outside if it was defined outside or to reassign it to parameter reg if it was passed as simple argument.

like image 21
eyquem Avatar answered Jan 02 '26 06:01

eyquem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!