在Python中通过方法进行字符串操作

在Python中通过方法进行字符串操作,python,string,list,indexing,sentence,Python,String,List,Indexing,Sentence,从类句子开始,我尝试创建多个方法,这些方法将打印字符串中的所有单词,在索引中返回一个单词,并在索引中替换一个单词(等等)。我很难理解self在整个方法中的用法,最后调用方法 class Sentence: def __init__(self, sentence = ''): '''default value for private attribute (sentence) = empty string''' self._sentence_str = sen

从类句子开始,我尝试创建多个方法,这些方法将打印字符串中的所有单词,在索引中返回一个单词,并在索引中替换一个单词(等等)。我很难理解self在整个方法中的用法,最后调用方法

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?
你不能简单地返回self.s,你应该返回整个self.statement\u str.split(“”)
或者像我那样把它赋给一个变量,这没有任何区别。

看看这篇文章,它似乎是你需要的,并且已经回答了
    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