Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Regular Expressions in Python Introduction to Regular Expressions Escape Hatches

Re.Search Not Giving Desired Output

Hi there,

Here's what I wrote:-

import re

a = open("names.txt")

data = a.read()

a.close()

print(re.match(r'Love',data))

print(re.search(r'\w, \w',data))

print (re.search(r'\d\d\d',data))

Here's the Output (python re1.py):-

<_sre.SRE_Match object at 0x10ec684a8>

<_sre.SRE_Match object at 0x10ec684a8>

<_sre.SRE_Match object at 0x10ec684a8>

I can't get the actual content which should be the names and numbers from the file.

Could you please revert with the answer?

Thanks Harmeet

1 Answer

Hello Harmeet,

to me it looks like you are using Python 2, since Python 3 gives me a better output: in Python 3, I would get for this example:

>>>m = re.match('[\w]*', 'hello')
>>>print(m)
<_sre.SRE_Match object; span=(0, 5), match='hallo'>

But in Python 2 I get these other match objects, that you get. You can always look for the methods of an object by using dir: this includes the string method in python 2, so in python2 this would look like this:

>>>m = re.match('[\w]*', 'hello')
>>>dir(m)
[..., string, ... ]
>>>m.string
'hello'

just use the command line and try yourself and consider switching to python3, for which I need to just call 'python3' on my terminal instead of just 'python'.

Hope this helps, otherwise, please let me know with regards, Sabine