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

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 67,989 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.