I am getting started learning Python3 and currently I am totally lost in 'regular expressions'. In order to understand raw strings I wrote this code:
import re
pattern='\\n'
c='qwerty\. i am hungry. \n z'
d=r'qwerty\. i am hungry. \n z '
print(c)
print(d+'\n\n\n')
for a in (c,d,):
if re.search(pattern,a):
print('"{0}" contains "{1}" \n'.format(a, pattern))
else:
print('"{0}" does not contain "{1}" \n'.format(a, pattern))
Output is: first string contains pattern and the second doesn't. However, once I introduce a minor change in the pattern:
import re
pattern=r'\\n'
c='qwerty\. i am hungry. \n z'
d=r'qwerty\. i am hungry. \n z '
print(c)
print(d+'\n\n\n')
for a in (c,d,):
if re.search(pattern,a):
print('"{0}" contains "{1}" \n'.format(a, pattern))
else:
print('"{0}" does not contain "{1}" \n'.format(a, pattern))
The result gets reversed. The second string contains r'\\n'
, which I cannot understand, since there is no double backslash in it...
Could you please explain this mystery to me?