Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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