i am very new to regular expression and trying get “\” character using python
normally i can escape “\” like this
print ("\\");
print ("i am \\nit");
output
\
i am \nit
but when i use the same in regX it didn’t work as i thought
print (re.findall(r'\\',"i am \\nit"));
and return me output
['\\']
can someone please explain why
EDIT: The problem is actually how
printworks with lists & strings. It prints the representation of the string, not the string itself, the representation of a string containing just a backslash is'\\'. Sofindallis actually finding the single backslash correctly, butprintisn’t printing it as you’d expect. Try:(The following is my original answer, it can be ignored (it’s entirely irrelevant), I’d misinterpreted the question initially. But it seems to have been upvoted a bit, so I’ll leave it here.)
The
rprefix on a string means the string is in “raw” mode, that is,\are not treated as special characters (it doesn’t have anything to do with “regex”).However,
r'\'doesn’t work, as you can’t end a raw string with a backslash, it’s stated in the docs:But you actually can use a non-raw string to get a single backslash:
"\\".