The problem with using match() here is that it is anchored to the beginning of the string. You want to find a single special character anywhere in the string, so use search() instead:

def no_special_characters(s, pat=re.compile('[@_!#$%^&*()<>?/\|}{~:]')):
    if pat.search(s):
        print(s + " has special characters")
    else:
        print(s + " has NO special characters")

You could also keep using match() with the following regex pattern:

.*[@_!#$%^&*()<>?/\|}{~:].*
Answer from Tim Biegeleisen on Stack Overflow
🌐
Finxter
blog.finxter.com › home › learn python blog › regex special characters – examples in python re
Regex Special Characters - Examples in Python Re - Be on the Right Side of Change
June 19, 2022 - For example, the pattern .*txt matches an arbitrary number of arbitrary characters followed by the suffix 'txt'. This pattern has two special regex meta characters: the dot . and the asterisk operator *. You’ll now learn about those meta characters: Feel free to watch the short video about the most important regex meta characters: Next, you’ll get a quick and dirty overview of the most important regex operations and how to use them in Python.
Discussions

Regex for all special characters
Do the special characters need to be separated by spaces when put into the list? Or, can they be one after the other like that · I would encourage you to try out a test site as well where you can paste in your regex and test strings and make sure they trigger as expected. More on community.spiceworks.com
🌐 community.spiceworks.com
4
1
June 8, 2024
regex - Python: How to match special characters in regular expression? - Stack Overflow
I'm trying to do a regular expression match with special characters in it, such as "/", ".", and "-". This is the string: 17440 root 20 0 3645m 452m 12m S 152 11.8 347:32.04 test/1/02.3_... More on stackoverflow.com
🌐 stackoverflow.com
Using regex with special characters to find a match in python - Stack Overflow
933 Regex for password must contain at least eight characters, at least one number and both lower and uppercase letters and special characters · 1479 How do I find the location of my Python site-packages directory? More on stackoverflow.com
🌐 stackoverflow.com
July 26, 2017
Which special characters must be escaped when using Python regex module re? - Stack Overflow
I'm using the Python module re to write regular expressions for lexical analysis. I've been looking for a comprehensive list of which special characters must be escaped in order to be recognized by the regex to no avail. More on stackoverflow.com
🌐 stackoverflow.com
🌐
NTU Singapore
www3.ntu.edu.sg › home › ehchua › programming › howto › Regexe.html
Regular Expression (Regex) Tutorial
The characters listed above have special meanings in regex. To match these characters, we need to prepend it with a backslash (\), known as escape sequence. For examples, \+ matches "+"; \[ matches "["; and \. matches ".". Regex also recognizes common escape sequences such as \n for newline, ...
🌐
TutorialsPoint
tutorialspoint.com › how-to-use-special-characters-in-python-regular-expression
How to use special characters in Python Regular Expression?
From Python documentation · Non-special characters match themselves. Special characters don't match themselves − · After '[', enclose a set, the only special chars are − · Quantifiers (append '?' for non-greedy) − · Rajendra Dharmkar · Updated on: 2020-06-13T07:12:45+05:30 ·
🌐
Plain English
python.plainenglish.io › how-to-handle-special-characters-in-python-regex-8ec125a292f0
How to Handle Special Characters in Python RegEx? | Python in Plain English
January 20, 2025 - By the end of this article, you’ll have a thorough understanding of how to effectively use special characters in Python RegEx. In RegEx, special characters have a specific meaning and are used to define patterns for searching and matching. These characters allow you to create more dynamic patterns that can match multiple forms of text.
🌐
Spark By {Examples}
sparkbyexamples.com › home › python › python regex replace special characters
Python regex replace special characters - Spark By {Examples}
May 31, 2024 - How to replace special characters in Python using regex? As you are working with strings, you might find yourself in a situation where you want to replace
Find elsewhere
🌐
Stack Overflow
stackoverflow.com › questions › 27031076 › python-how-to-match-special-characters-in-regular-expression
regex - Python: How to match special characters in regular expression? - Stack Overflow
Do I need backslash before the special characters, such as "/" and "."? Thanks! ... You need to change (?P<mem>\d.+) in your regex to (?P<mem>[\d.]+) so that it would capture a digit or a dot one or more times or otherwise \d.+ would match a digit and the following characters greedily.
🌐
PYnative
pynative.com › home › python › regex › python regex special sequences and character classes
Python Regex Special Sequences and Character classes
May 28, 2022 - Python regex special sequence represents some special characters to enhance the capability of a regulars expression. ... The special sequence represents the basic predefined character classes, which have a unique meaning. Each special sequence makes specific common patterns more comfortable to use.
🌐
TutorialsPoint
tutorialspoint.com › article › How-to-escape-any-special-character-in-Python-regular-expression
How to escape any special character in Python regular expression?
April 4, 2023 - The outcome is the same as before when we follow this with \1 for the initial capture. Backslash () serves two functions in Regex: in the case of metacharacters like d (digit), D (non-digit), s (space), S (non-space), w (word), and W (non-word).
🌐
John D. Cook
johndcook.com › blog › 2019 › 08 › 31 › regex-special-characters
Regular expressions and special characters
September 1, 2019 - Rather than treat it as a special string like Perl5, or a string that has to be separately compiled in almost all other languages that have regexes; it is a language all its own that lives at the same level as “regular” Perl6 code. (It actually borrows some syntax from regular Perl6 code.) So a direct translation of your code is relatively clear. ... Note that <()> causes it to “capture” the point before the character it matches.
🌐
Dataquest
dataquest.io › home › cheat sheets › python regex cheat sheet
Python Regex Cheat Sheet
July 22, 2025 - Matches characters from a to z and also from 0 to 9. ... Special characters become literal inside a set, so this matches (, +, *, and ).
🌐
Interfaceware
www-backup.interfaceware.com › manual › python_pattern_special_characters.html
Special Characters and Pattern Matching
Python allows you to specify a pattern to match when searching for a substring contained in a string. This pattern is known as a regular expression. For example, if you want to find a North American-style phone number in a string, you can define a pattern consisting of three digits, followed ...
🌐
Python
docs.python.org › 3.4 › library › re.html
6.2. re — Regular expression operations — Python 3.4.10 documentation
If the first character of the set is '^', all the characters that are not in the set will be matched. For example, [^5] will match any character except '5', and [^^] will match any character except '^'. ^ has no special meaning if it’s not the first character in the set.
🌐
MojoAuth
mojoauth.com › escaping › regex-escaping-in-python
Regex Escaping in Python | Escaping Methods in Programming Languages
To implement regex escaping in Python, you can use the re module, which provides functionalities for working with regex. The re.escape() function is particularly useful, as it automatically escapes all non-alphanumeric characters in a given string.
🌐
W3Schools
w3schools.com › python › python_regex.asp
Python RegEx
Python has a built-in package called re, which can be used to work with Regular Expressions. ... You can add flags to the pattern when using regular expressions. A special sequence is a \ followed by one of the characters in the list below, ...
🌐
Python documentation
docs.python.org › 3 › library › re.html
re — Regular expression operations — Python 3.14.6 ...
May 25, 2026 - The solution is to use Python’s raw string notation for regular expression patterns; backslashes are not handled in any special way in a string literal prefixed with 'r'. So r"\n" is a two-character string containing '\' and 'n', while "\n" is a one-character string containing a newline.
Top answer
1 of 7
268

Use re.escape

>>> import re
>>> re.escape(r'\ a.*$')
'\\\\\\ a\\.\\*\\$'
>>> print(re.escape(r'\ a.*$'))
\\\ a\.\*\$
>>> re.escape('www.stackoverflow.com')
'www\\.stackoverflow\\.com'
>>> print(re.escape('www.stackoverflow.com'))
www\.stackoverflow\.com

Repeating it here:

re.escape(string)

Return string with all non-alphanumerics backslashed; this is useful if you want to match an arbitrary literal string that may have regular expression metacharacters in it.

As of Python 3.7 re.escape() was changed to escape only characters which are meaningful to regex operations.

2 of 7
23

I'm surprised no one has mentioned using regular expressions via re.sub():

import re
print re.sub(r'([\"])',    r'\\\1', 'it\'s "this"')  # it's \"this\"
print re.sub(r"([\'])",    r'\\\1', 'it\'s "this"')  # it\'s "this"
print re.sub(r'([\" \'])', r'\\\1', 'it\'s "this"')  # it\'s\ \"this\"

Important things to note:

  • In the search pattern, include \ as well as the character(s) you're looking for. You're going to be using \ to escape your characters, so you need to escape that as well.
  • Put parentheses around the search pattern, e.g. ([\"]), so that the substitution pattern can use the found character when it adds \ in front of it. (That's what \1 does: uses the value of the first parenthesized group.)
  • The r in front of r'([\"])' means it's a raw string. Raw strings use different rules for escaping backslashes. To write ([\"]) as a plain string, you'd need to double all the backslashes and write '([\\"])'. Raw strings are friendlier when you're writing regular expressions.
  • In the substitution pattern, you need to escape \ to distinguish it from a backslash that precedes a substitution group, e.g. \1, hence r'\\\1'. To write that as a plain string, you'd need '\\\\\\1' — and nobody wants that.