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(),分别是用来删除开头的“其他字符”的

 

 

 

 

 

  • 4
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值