python中re模块中体重了基于模式的字符串处理能力,比如替换字符串,以及根据界定符对字符串进行分解等。
- import re
- tststr = 'This sentence ends in 5 stars *****'
- str1 = "1,2,3,4,5,6,7"
- str2 = "1+2x*3-y"
- formatstr = '%-34s: %s' # string to format output
- print formatstr % ("Original string" ,tststr)
- tststr = re.sub( r'\*' , r'^' , tststr) #替换子字符串
- print formatstr % ( '^ substitute for *' , tststr)
- tststr = re.sub( r'stars' , 'carets' , tststr )
- print formatstr % ('carets substitute for stars' , tststr)
- tststr = formatstr % ( "Every word replaced by 'hello'" ,
- re.sub(r'\w+' , 'hello' , tststr) )
- print formatstr % ('Replace str1 first 3 digits by "digit"' ,
- re.sub(r'\d' , 'digit' , str1 , 3) ) #将数字进行替换,并指定替换的最多次数
- print formatstr % ('Splitting' + str1 , re.split(r',' , str1))
- print formatstr % ("Splitting " + str2 , re.split(r'[+\-*/%]' , str2))
- #类只能个出现的任何字符(^ 和 - 除外)都会被解释成字面意义的字符,所以 $ , + , * 等元字符无需转义
- 运行结果如下:
- Original string : This sentence ends in 5 stars *****
- ^ substitute for * : This sentence ends in 5 stars ^^^^^
- carets substitute for stars : This sentence ends in 5 carets ^^^^^
- Replace first 3 digits by "digit" : digit,digit,digit,4,5,6,7
- Splitting1,2,3,4,5,6,7 : ['1', '2', '3', '4', '5', '6', '7']
- Splitting 1+2x*3-y : ['1', '2x', '3', 'y']
阅读(977) | 评论(0) | 转发(0) |