Mega Code Archive

 
Categories / Python Tutorial / Regular Expressions
 

Regular-expression string manipulation

import re testString1 = "This sentence ends in 5 stars *****" testString2 = "1,2,3,4,5,6,7" testString3 = "1+2x*3-y" formatString = "%-34s: %s"   # string to format output print formatString % ( "Original string", testString1 ) testString1 =  re.sub( r"\*", r"^", testString1 ) print formatString % ( "^ substituted for *", testString1 ) testString1 = re.sub( r"stars", "carets", testString1 ) print formatString % ( '"carets" substituted for "stars"',testString1 ) print formatString % ( 'Every word replaced by "word"',re.sub( r"\w+", "word", testString1 ) ) print formatString % ( 'Replace first 3 digits by "digit"',re.sub( r"\d", "digit", testString2, 3 ) ) print formatString % ( "Splitting " + testString2,re.split( r",", testString2 ) ) print formatString % ( "Splitting " + testString3,re.split( r"[+\-*/%]", testString3 ) )