Python re. sub

Source: Internet
Author: User

Python re. subIt is a standard library of Python regular expressions. Its main function is to use regular expressions to match strings to be replaced.
Then replace it with the desired string method.
The following is an example:
Import re
Link =Re. Compile("\ D + ")
Content = "laowang-222haha"
Info = Re. sub (link, 'www .cnpythoner.com ', content)
Print info
Info string is replaced


The Re. sub function performs replacement based on a regular expression.

1. >>> import re
2. >>> re. Search ('[ABC]', 'mark ')
3. <_ SRE. sre_match object at 0x001c1fa8>
4. >>> re. sub ('[ABC]', 'O', 'mark ')
5. 'mork'
6. >>> re. sub ('[ABC]', 'O', 'Rock ')
7. 'rook'
8. >>> re. sub ('[ABC]', 'O', 'caps ')
9. 'ops'

Does Mark contain A, B, or C? Yes, it contains.

Okay. Now find A, B, or C and replace it with O. Mark becomes Mork.

The same method can change rock to rook.

You may think it can change caps to OAPs, but this is not the case. Re. sub replaces all matching items, not just the first matching item. Therefore, the regular expression converts caps to oops, because both C and A are converted to O.

For more information, see Python replacement or [String replacement].

ArticleReprinted: http://www.cnpythoner.com/post/19.html

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.