1. 程式人生 > >Python中的替換函式---replace(),re.sub()和strip()

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(),分別是用來刪除開頭的“其他字元”的