零基础写python爬虫之神器正则表达式

2019-10-05 14:45:27王振洲

count用于指定最多替换次数,不指定时全部替换。


import re 
  
p = re.compile(r'(w+) (w+)') 
s = 'i say, hello world!' 
  
print p.sub(r'2 1', s) 
  
def func(m): 
    return m.group(1).title() + ' ' + m.group(2).title() 
  
print p.sub(func, s) 
  
### output ### 
# say i, world hello! 
# I Say, Hello World! 

7.subn
subn(repl, string[, count]) |re.sub(pattern, repl, string[, count]):
返回 (sub(repl, string[, count]), 替换次数)。


import re 
  
p = re.compile(r'(w+) (w+)') 
s = 'i say, hello world!' 
  
print p.subn(r'2 1', s) 
  
def func(m): 
    return m.group(1).title() + ' ' + m.group(2).title() 
  
print p.subn(func, s) 
  
### output ### 
# ('say i, world hello!', 2) 
# ('I Say, Hello World!', 2) 

以上就是python神器正则表达式的基本介绍了,非常简单实用吧,希望对大家有所帮助^_^