Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking a python string for escaped characters

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?

like image 444
Andrew Avatar asked Jul 31 '15 05:07

Andrew


People also ask

How do you show escape characters in Python?

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.

How do you check if a string does not contain special characters Python?

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.

How do you check if a string contains a specific character in Python?

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 = '. '


1 Answers

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.
like image 106
falsetru Avatar answered Sep 30 '22 07:09

falsetru