3
>>> import re
>>> a='''\\n5
... 8'''
>>> b=re.findall('\\n[0-9]',a)
>>> print(b)
['\n8']

Why does it show \n8 and not \n5? I used a \ in front of \n the first time. I am finding the use of raw string in regex in python a bit confusing. To me it does not seem to be making any changes to the result

Mohd
  • 5,523
  • 7
  • 19
  • 30
Vaibhav
  • 103
  • 8

3 Answers3

2

\\n is not a newline, it's an escaped backslash with an n.

>>> import re
>>> a = '''\n5
... 8'''
>>> a=re.findall('\\n[0-9]',a)
>>> print(a)
['\n5', '\n8']
rinkert
  • 6,593
  • 2
  • 12
  • 31
2

This is because in strings, the newline character is considered that, a single character.

When you do \\n5 you're escaping the \, so that's literally printing \n5, and not a newline by Python standards.

When you search for a regex such as \\n[0-9] though, in the first \ you're escaping the \n regex expression, so in the end you're looking for \n which is Python's newline. That matches the actual newline in your string, but not \\n which is two separate characters, an escaped \ and an n.

1

because \\n5 is not valid new line, it will print \n5

uingtea
  • 6,002
  • 2
  • 26
  • 40