I'm trying to check if a string in python contains escaped characters. The simplest way to do this is to set a list of escaped characters, then check if any element in the list is in the string:
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 of doing this?
We have many escape characters in Python like \n, \t, \r, etc., What if we want to print a string which contains these escape characters? We have to print the string using repr() inbuilt function. It prints the string precisely what we give.
re. match() to detect if a string contains special characters or not in Python. This is function in RegEx module. It returns a match when all characters in the string are matched with the pattern(here in our code it is regular expression) and None if it's not matched.
Using in operator The Pythonic, fast way to check for the specific character in a string uses the in operator. It returns True if the character is found in the string and False otherwise. ch = '. '
You can use regular expression (See also re
module 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'
&
, ;
matches &
, ;
literally.\w
matches word character (alphabet, digits, _
).\w+
matches one or more word characters.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With