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

相关文章
相关标签/搜索