"Python Cookbook" "String and Text" 5. Find and Replace text

Source: Internet
Author: User

Problem: Finding and replacing text in a string

Solution:

1. For simple mode: str.replace (old, new[, Max])

2. Complex mode: Use the re.sub ( matching mode , newstring, oldstring[, replace number]) function in the RE module

3, RE.SUBN () can get the total number of replacements

#example.py##Examples of simple regular expression substitutionImportRe#Simple Sampletext1='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 TextText ='Today is 11/27/2012. Pycon starts 3/13/2013.'Datepat= Re.compile (r'(\d+)/(\d+)/(\d+)')#(a) simple substitution \3-represents the 3rd pattern group in a matching patternPrint(Datepat.sub (R'\3-\1-\2', text)) #equivalent to print (Re.sub (R ' (\d+)/(\d+)/(\d+) ', R ' \3-\1-\2 ', text))Print('*****************************')
#(b) Replacement function substitution callback functions fromCalendarImportMonth_abbrdefchange_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('++++++++++++++++++++++++++++++++')

# Total number of replacements obtained by 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 yehyeah,but yes,but yeah,but yes,but yeah,but no,but yeah------------------------- - -is 2012-11-27. Pycon starts 2013-3-13.   is 2012. Pycon starts is 2012. Pycon starts. ++++++++++++++++++++++++++++++++ is 2012-11-27. Pycon starts 2013-3-13.

Python Cookbook "String and Text" 5. Find and replace text

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.