python中字符串的rstrip()方法

今天在刷Bite 105. Slice and dice時遇到的一個問題,判斷一個字符串是否以'.'或者'!'結尾,若是以這兩個字符結尾,則去除這兩個字符。
本身寫的函數:python

results = []
    text_list = text.split('\n')
    print(text_list)
    for line in text_list:
        if line:
            new_line = line.strip()
            if new_line[0] in ascii_lowercase:
                line_list = new_line.split(' ')
                if line_list[-1][-1] != '.' and line_list[-1][-1] != '!':
                    results.append(line_list[-1])
                else:
                    results.append(line_list[-1][0:-1])
    return results

能夠看到,在判斷和去除這兩個字符的時候,用了比較笨的方法,就是直接取字符串的[0:-1],後來查資料發現,python字符串中提供了rstrip()方法能夠直接實現該功能,修改後的代碼以下:app

results = []
    for line in text.strip().split('\n'):
        line = line.strip()

        if line[0] not in ascii_lowercase:
            continue
        words = line.split()

        last_word_stripped = words[-1].rstrip('!.')
        results.append(last_word_stripped)

    return results

查看了該方法的實現:函數

def rstrip(self, *args, **kwargs): # real signature unknown
        """
        Return a copy of the string with trailing whitespace removed.
        
        If chars is given and not None, remove characters in chars instead.
        """
        pass

發現若是沒有給該方法傳參數,該方法會默認去掉字符串結尾的空格,若是傳參了,就會去掉字符串中以傳參結尾的。
其實該練習中,還有ascii_lowercase值得注意,能夠用來判斷是否爲小寫字母!!!spa

相關文章
相關標籤/搜索