Python中的替换函数---replace(),re.sub()和strip()

这是原文,写的很好,共勉!

1. replace()

对象.replace(rgExp, replaceText, max)
  • rgExpreplaceText是必须要有的,max是可选的参数,可以不加
  • 在对象的每个rgExp都替换成replaceText,从左到右最多max次

比如:

class Solution:
    def replace_space(self, s):
        if not s:
            return False
        # 对象.replace(rgExp,replaceText,max)
        ss = s.replace(' ', '20%')
        return ss
if __name__ == '__main__':
    strings = 'We Are Happy'
    s = Solution()
    print s.replace_space(strings)
>>> We20%Are20%Happy

2. re.sub---substitute,进行相对复杂的字符串替换

详细请看这

要用sub(),记住要import re哦!

re.sub(pattern,repl,string,count,flags)
  • 三个必选参数:pattern,repl,string,两个可选参数:count,flags
  1. pattern:  正则表达式中的模式字符串;
  2. repl:       原来字符串中要换的东西,比如上面例子中的20%(既可以是字符串,也可以是函数);
  3. string:    要被处理的,要被替换的字符串,比如上面例子中的strings,即:'We Are Happy';
  4. count:    匹配的次数,最多的次数
  5. flages:   标志位,用于控制正则表达式的匹配方式,如是否区分大小写,多行匹配等等

比如:

import re
class Solution:
    def replace_space(self, s):
        if not s:
            return False
        pattern = re.compile(r' ')
        # re.sub(pattern,repl,string,count,flags)
        return re.sub(pattern, r'20%', s)
if __name__ == '__main__':
    strings = 'We Are Happy'
    s = Solution()
    print s.replace_space(strings)

3. strip()

strip()并不是一个真正意义上的替换函数,它是用来删除一些字符的,所以我们可以把这看作是把字符串中的一些字符替换成空(不是空格,是空

  1. 开头和结尾的空格都被去掉了,并不能删除字符串中间的空格(注意字符串首位是否会有空格)
  2. lstrip()和rstrip(),分别是用来删除开头的“其他字符”的

猜你喜欢

转载自blog.csdn.net/Mr_XiaoZ/article/details/81806295