>>> p =re.compile( r'\W+') >>> p.split( 'This is a test, short and sweet, of split(). ') ['This', 'is', 'a', 'test', 'short', 'and', 'sweet', 'of', >>> p.split( 'This is a test, short and sweet, of split(). ',3) ['This', 'is', 'a', 'test, short and sweet, of split().'] >>> p =re.compile( r'\W+') >>> p2=re.compile( r'(\W+) ') >>> p.split( 'This... is a test. ') ['This', 'is', 'a', 'test', ''] >>> p2.split( 'This... is a test. ') ['This', '... ', 'is', ' ', 'a', ' ', 'test', '.', ''] >>> re.split( r'[\W]+','Words, words, words. ') ['Words', 'words', 'words', ''] >>> re.split( r'([\W]+) ','Words, words, words. ') ['Words', ', ', 'words', ', ', 'words', '.', ''] >>> re.split( r'[\W]+','Words, words, words. ',1) ['Words', 'words, words.'] >>> p =re.compile( '(blue|white|red)') >>> p.sub('colour','blue socks and red shoes') 'colour socks and colour shoes' >>> p.sub('colour','blue socks and red shoes', count =1) 'colour socks and red shoes' >>> p =re.compile( '(blue|white|red)') >>> p.subn( 'colour','blue socks and red shoes') ('colour socks and colour shoes', 2) >>> p.subn( 'colour','no colours at all ') ('no colours at all', 0) >>> p =re.compile( 'x*') >>> p.sub('-','abxd') '-a-b--d-' 15 Empty matches are replaced only when they’re not adjacent to a previous empty match. The$_{subn()}$ method does the same work, but returns a 2-tuple containing the new string value and the number of replacements that were performed: Here’s a simple example of using the$_{sub()}$ method. It replaces colour names with the word$_{colour}$: 5.2 Search and Replace Sometimes you’re not only interested in what the text between delimiters is, but also need to know what the delimiter was. If capturing parentheses are used in the RE, then their values are also returned as part of the list. Compare the following calls: The module-level function re.split() adds the RE to be used as the first argument, but is otherwise the same. Another common task is to find all the matches for a pattern, and replace them with a different string. The$_{sub()}$ method takes a replacement value, which can be either a string or a function, and the string to be processed. The optional argument count is the maximum number of pattern occurrences to be replaced; count must be a non-negative integer. The default value of 0 means to replace all occurrences. . sub ( replacement , string [, count=0 ] ) Returns the string obtained by replacing the leftmost non-overlapping occurrences of the RE in string by the replacement replacement . If the pattern isn’t found, string is returned unchanged.