Python string check for escaped characters

I am trying to check if a string in python contains escaped characters. The easiest way to do this is to set up a list of escaped characters, and then check to see if any item in the list is on the line:

s = "A & B" escaped_chars = ["&", """, "'", ">"] for char in escaped_chars: if char in s: print "escape char '{0}' found in string '{1}'".format(char, s) 

Is there a better way to do this?

+5
source share
1 answer

You can use regex (see also re modulo documentation ):

 >>> s = "A & B" >>> import re >>> matched = re.search(r'&\w+;', s) >>> if matched: ... print "escape char '{0}' found in string '{1}'".format(matched.group(), s) ... escape char '&' found in string 'A & B' 
  • & ; literally matches & ; .
  • \w matches the word character (alphabet, numbers, _ ).
  • \w+ matches one or more word characters.
+6
source

All Articles