How to escape special characters of a string with single backslashes [duplicate]

This is one way to do it (in Python 3.x):

escaped = a_string.translate(str.maketrans({"-":  r"\-",
                                          "]":  r"\]",
                                          "\\": r"\\",
                                          "^":  r"\^",
                                          "$":  r"\$",
                                          "*":  r"\*",
                                          ".":  r"\."}))

For reference, for escaping strings to use in regex:

import re
escaped = re.escape(a_string)

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)