python中字符串的rstrip()方法

栏目: Python · 发布时间: 6年前

内容简介:今天在刷Bite 105. Slice and dice时遇到的一个问题,判断一个字符串是否以'.'或者'!'结尾,如果以这两个字符结尾,则去除这两个字符。自己写的函数:可以看到,在判断和去除这两个字符的时候,用了比较笨的方法,就是直接取字符串的[0:-1],后来查资料发现,python字符串中提供了rstrip()方法可以直接实现该功能,修改后的代码如下:

今天在刷Bite 105. Slice and dice时遇到的一个问题,判断一个字符串是否以'.'或者'!'结尾,如果以这两个字符结尾,则去除这两个字符。

自己写的函数:

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()方法可以直接实现该功能,修改后的代码如下:

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值得注意,可以用来判断是否为小写字母!!!


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

The Tangled Web

The Tangled Web

Michal Zalewski / No Starch Press / 2011-11-26 / USD 49.95

"Thorough and comprehensive coverage from one of the foremost experts in browser security." -Tavis Ormandy, Google Inc. Modern web applications are built on a tangle of technologies that have been de......一起来看看 《The Tangled Web》 这本书的介绍吧!

在线进制转换器
在线进制转换器

各进制数互转换器

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具