Design a class called "sentence" that have a constructor that takes a string representing the sentence as input. The class should have the following methods:
get_first_word
get_all_words
replace(index, new_word) Change a word at a particular index to "new_word." E.g. If the sentence is " I'm going back." and set_word_at_index (2, "home"), then the sentence becomes "I'm going home."

someone explain to me I am little confused about the input.

Recommended Answers

All 3 Replies

Your input to the class is your sentence/text, so put that into the class constructor __init__() as a parameter after self. Note that by convention class names are capitalized, it makes code much more readable:

class Sentence:
    def __init__(self, text):
        self.text = text

    def get_first_word (self):
        word_list = self.text.split()
        return word_list[0]


# create an instance
# Sentence(text)
# this is your input text
text = "Listen to the whisper, or wait for the brick." 
sent1 = Sentence(text)

print(sent1.get_first_word())  # Listen

# set up another instance
text = "My karma ran over your dogma." 
sent2 = Sentence(text)

print(sent2.get_first_word())  # My

I am trying to print "I'm going back" first sentence and at the end "I'm going home"

this is what prints out and I am missing "going"

I'm
home.

Hint:

class Sentence:
    def __init__(self, text):
        self.text = text
        self.word_list = self.text.split()
        #print(self.word_list)  # test

    def get_first_word (self):
        return self.word_list[0]

    def get_all_words(self):
        "I let you work out what to return"
        pass

# create an instance of class Sentence(text)
# this is your input text
text = "I'm going back" 
sent1 = Sentence(text)

print(sent1.get_first_word())  # I'am

# get the whole text
print(sent1.text)  # I'm going back

# a hint for module sent1.get_all_words()
# create the words from self.word_list
for word in sent1.word_list:
    print(word)

'''
I'm
going
back
'''
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.