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

Kishore Kumar
Kishore Kumar
5,451 Points

Reading Files

I am using the same code that Kenneth is using but not getting the same o/p. I am using pycharm to run my code.

Code:

import re

name_file = open("names.txt", encoding="utf-8")
data = name_file.read()
name_file.close()
# print(data)
# last_name = r'Love'
# first_name = r'Kenneth'
print(re.match(r'Love', data))
print(re.search(r'Kenneth', data))

o/p:

C:\Users\Kishore\AppData\Local\Programs\Python\Python35-32\python.exe C:/Users/Kishore/PycharmProjects/RegularExpression/address_book.py

None
<_sre.SRE_Match object; span=(7, 14), match='Kenneth'>

Process finished with exit code 0
Chris Freeman
Chris Freeman
Treehouse Moderator 68,457 Points

Hi Kishore, can you add what output you were expecting?

The match returns None since the entire data does not match "Love" exactly.

Did you intend to use groups by adding parens to mark group?

>>> print(re.search(r'(Love)', string).groups())
('Love',)
>>> 

1 Answer

re.match only matches the beginning of a string. re.search matches anywhere in the string.