• 【python cookbook】【字符串与文本】5.查找和替换文本


    问题:对字符串中的文本做查找和替换

    解决方案:

    1、对于简单模式:str.replace(old, new[, max])

    2、复杂模式:使用re模块中的re.sub(匹配的模式, newstring, oldstring[,替换个数])函数

    3、re.subn()可以获得替换的总次数

    # example.py
    #
    # Examples of simple regular expression substitution
    
    import re
    
    #simple sample
    text1='yeah,but no,but yeah,but no,but yeah,but no,but yeah'
    print (text1.replace('yeah','yeh'))
    print (text1.replace('no','yes',2))
    print ('---------------------------')
    # Some sample text text = 'Today is 11/27/2012. PyCon starts 3/13/2013.' datepat = re.compile(r'(d+)/(d+)/(d+)') # (a) Simple substitution 3-表示匹配的模式中第3个模式组 print(datepat.sub(r'3-1-2', text)) #等价于print (re.sub(r'(d+)/(d+)/(d+)',r'3-1-2', text)) print ('*****************************')
    # (b) Replacement function 替换回调函数 from calendar import month_abbr def change_date(m): mon_name = month_abbr[int(m.group(1))] return '{} {} {}'.format(m.group(2), mon_name, m.group(3)) print(datepat.sub(change_date, text)) print (re.sub(r'(d+)/(d+)/(d+)',change_date, text)) print ('++++++++++++++++++++++++++++++++')

    # 通过re.subn()获取替换的总次数
    newtext,n=datepat.subn(r'3-1-2', text) 
    print (newtext)
    print (n)
    >>> ================================ RESTART ================================
    >>> 
    yeh,but no,but yeh,but no,but yeh,but no,but yeh
    yeah,but yes,but yeah,but yes,but yeah,but no,but yeah
    ---------------------------
    Today is 2012-11-27. PyCon starts 2013-3-13.
    *****************************
    Today is 27 Nov 2012. PyCon starts 13 Mar 2013.
    Today is 27 Nov 2012. PyCon starts 13 Mar 2013.
    ++++++++++++++++++++++++++++++++
    Today is 2012-11-27. PyCon starts 2013-3-13.
    2
    >>> 
  • 相关阅读:
    游千佛塔有感
    时刻坚持高标准:成大事者的十条“箴言”
    谁愿意嫁给我这样的人
    成功的秘诀之一,就是敢于提出大设想、大思考
    寒冬里的暖阳
    世界最伟大的管理原则
    把你藏在心里
    登天门有感
    办公室保持最佳状态的诀窍
    “领悟”的价值是什么?思维能力训练问答
  • 原文地址:https://www.cnblogs.com/apple2016/p/5790780.html
Copyright © 2020-2023  润新知