Regular-expression string manipulation. : Split « Regular Expressions « Python Tutorial






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 ) )








16.6.Split
16.6.1.with re.split you can split on any sequence of space characters and commas
16.6.2.The maxsplit argument indicates the maximum number of splits allowed:
16.6.3.Split Output of Unix who Command (rewho.py)
16.6.4.Use re package with text file
16.6.5.Regular-expression string manipulation.