Python Forum
Help with re.search()
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help with re.search()
#2
This is how I would go about it:

import re

class Book:
	def __init__(self, title):
		self.title = title

	def __str__(self):
		return self.title.title() + " is a great book!"

	def search_for_string(self, pattern):
		result = re.search (pattern, self.title)
		if result:
			return  result.group ()
		return None

book_list = []
book_list.append(Book('dune'))
book_list.append(Book('lord of the rings'))
book_list.append(Book('dragonlance'))
book_list.append(Book('return of the jedi'))

search_string = 'of the'

found = False
for book in book_list:
	found_string = book.search_for_string (search_string)
	if found_string:
		found = True
		print (f'"{found_string}" was found in the book title "{book.title}".')
if not found:
	print(f'Sorry. But no book titles match your search "{search_string}".')
Reply


Messages In This Thread
Help with re.search() - by Sigwulfr - Mar-22-2021, 07:48 PM
RE: Help with re.search() - by BashBedlam - Mar-22-2021, 07:56 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020