0

For teaching purposes, I would like a good explanation and example of why the "\" is needed in searching for, say a period or a character that python may interpret differently.

In the below example, I do NOT use a "\" to escape the "." and it still works fine.

def checkfordot():
    dotpattern="[.]"
    searchingfor=input("Enter string:")
    if (re.search(dotpattern,searchingfor)):
        print("Has a dot")
    else:
        print("Does not have a dot")

Output:

>>> checkfordot()
Enter string:dfsdf.
Has a dot
>>> checkfordot()
Enter string:ffsdfsdfsdf
Does not have a dot
>>> 

In this case, using dotpattern="[.]" or dotpattern="[.]" doesn't seem to make much difference.

Can someone a) explain why the above works without an escape and a simple explanation of what the escape does and in what situations b) provide an example or ideally two examples, integrated into my code, that demonstrates well why the escape character is required and how it is used for effective searching (or vice versa, in that without the "" the program would not work)

Ironically, in typing this out - I noticed I had to escape the \ in order for it to be printed. Here I am typing: >: " \ \ " ....but it prints just one backslash >"\"

Compoot
  • 2,227
  • 6
  • 31
  • 63
  • 1
    A dot is not a special char inside brackets, `[.]` = `\.`. Escaping a dot inside brackets is still not an issue, it will be parsed the same as if it were a dot. `[.]` = `[\.]`, but it makes little sense. – Wiktor Stribiżew Jul 21 '20 at 10:33
  • @WiktorStribiżew - I'd be so grateful for an example. Thank you for the above explanation but I need an example of when a dot needs to be escaped with a specific explanation. Even with the \...I don't see an explanation of what the \ does or how it is interpreted, if it is not escaped. – Compoot Jul 21 '20 at 10:35
  • Please read the posts I linked to at the top of your question. – Wiktor Stribiżew Jul 21 '20 at 10:35
  • It says "In a character class (square brackets) any character except ^, -, ] or \ is a literal." without explaining what a literal is. Taken literally? – Compoot Jul 21 '20 at 10:38
  • `a` is a literal text, literal char. `"\x61"` is also `a` text, but it is a string literal with a hex notation. – Wiktor Stribiżew Jul 21 '20 at 11:03

0 Answers0