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