-1

Why does this test fail?

import re
def test_Items():
    items = '''
    - item
    - item
    '''
    list_regex = re.compile(r"^- .*\n", re.MULTILINE)
    assert list_regex.match(items)

I'm having a hard time understanding the error message:

E       AssertionError: assert None
E        +  where None = <built-in method match of re.Pattern object at 0x7f8df4dbe240>('\
n    - item\n    - item\n    ')                                                          
E        +    where <built-in method match of re.Pattern object at 0x7f8df4dbe240> = re.co
mpile('^- .*\\n', re.MULTILINE).match                                                    
jjk
  • 592
  • 1
  • 6
  • 23

1 Answers1

0

The problem is that the string items begins with a newline and several spaces, and ends with several spaces. When using ''', the first character of the string starts immediately after the opening ''', and the last character of the string is immediately before the closing '''.

So items is:

'\n    - item\n    - item\n    '

You can fix it by doing:

    items = '''- item
- item
'''

Or you can do:

items = '- item\n- item\n'

Note that I also removed the leading spaces in the second line, as Baramar suggested.

Also note that re.match anchors the search at the start of the string. If you want to match any of the lines in the string, use re.search instead.

Tom Karzes
  • 22,815
  • 2
  • 22
  • 41
  • I think he should get rid of the indentation on all the lines, not just the first line. He's using `re.MULTILINE` so that `^` will match any of the newlines. – Barmar May 11 '20 at 18:08
  • @Barmar That's a good point, I removed the spaces from my examples. – Tom Karzes May 11 '20 at 18:09