Dec-10-2017, 06:59 AM
There are special characters that need to be escaped if you want to use them literally. The error comes at the
That said, note that you also need to escape chars like
\
which is RegEx own escape char. So the result is (when not escaped) is invalid pattern.import re, sre_constants patter = [chr(i) for i in range(33,126)] with open("a.txt","r") as file: content = file.read() for i in patter: try: result = len(re.findall(r"[%s]" % i,content)) except sre_constants.error: print('error with {}'.format(i))
Output:error with \
error with ^
change the for body like thistry: result = len(re.findall(r"[%s]" % i,content)) except sre_constants.error: result = len(re.findall(r"[\%s]" % i,content)) if result != 0: print("%s:%d" % (i, result))and it work.
That said, note that you also need to escape chars like
*
, ?
or .
in order to search for them literally. I will leave this to you