Search code examples
pythonstringlistindexingsentence

String Manipulation through methods in Python


Starting with class Sentence, I'm trying to create multiple methods that will print all the words in a string, return a word at an index, and replace a word at an index (and more). I'm having trouble understanding the use of self throughout the methods and calling methods at the end.

class Sentence:
    def __init__(self, sentence = ''):
        '''default value for private attribute (sentence) = empty string'''
        self._sentence_str = sentence
    def get_all_words(self):
        '''return all words in the sentence as a list'''
        self.s.split(" ")
        return self.s    
    def get_word(self, param):
        '''return only the word at a particular index'''
        '''arguments = index'''
        #Here, do I return an empty index so that I can call it/pick an index 
         at the end?
_sentence = Sentence("It feels like fall today")
print(_sentence)
index = self.index[2] #something like this? and print it?

Solution

  •     def __init__(self, sentence=''):
            
            '''default value for private attribute (sentence) = empty string'''
            self.sentence_str = sentence
        def get_all_words(self):
            '''return all words in the sentence as a list'''
            list = self.sentence_str.split(" ")
            return list    
            
        def get_word(self, index):
            '''return only the word at a particular index'''
            list = self.get_all_words() #split
            return list[index]  #this is how you access a list item by it's index: list[index]
    
        def replace_word(self, word, new_word):
            list = self.get_all_words()   # split
            current_word_index = list.index(word) #find in what index the word you want to change lives
            list[current_word_index] = new_word # replace the current word in current_word_index with the new word
            return ' '.join(list) #optional: you can return an actual string instead of a list, use return list if you want a list
            
            
    sentence = Sentence("It feels like fall today")
    
    print(sentence.get_all_words()) #this will return the string as a list
    print(sentence.get_word(2)) # this will return an item at a certain index
    print(sentence.replace_word('fall', 'summer')) #this will replace a word
    
    

    you can't simply return self.s, you should return the whole self.sentence_str.split(" ") or assign it to a variable like I did, It doesn't make any difference tho.