Python Forum
Help with re.search() - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Homework (https://python-forum.io/forum-9.html)
+--- Thread: Help with re.search() (/thread-33013.html)



Help with re.search() - Sigwulfr - Mar-22-2021

Hi

I need help writing a re.search() method inside the Book class (see below), that will allow me to search for a string or part of a string, and return whether one of the three books has a title that matches or partly matches the search string. Something like:

    def search_string(what do I enter here?):
        if re.search(what do I enter here?) 
            return print(f"{search_string} has been found in the following book titles: {self.title.title()}")
        else:
            return print(f"Sorry. But no book titles match your search {search_string}")
import re
class Book:
    def __init__(self, title):
        self.title = title
    def __str__(self):
        return self.title.title() + " is a great book!"

dune = Book('dune')
lotr = Book('lord of the rings')
dragonlance = Book('dragonlance')
print(dune)
I hope you can help me out.

In advance, thanks for helping me out.

Best regards Chris


RE: Help with re.search() - BashBedlam - Mar-22-2021

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}".')