高级的模板可以修改string.Template的默认语法,为此需要调整它在模板中查找变量名所使用的正则表达式。
############################################################# #test about matetrans() leet = string.maketrans('asdfghjk', '12345678') print s.translate(leet) print s ############################################################# #test about Template() values = {'var':'foo'} t=string.Template(""" Variable : $var Escape : $$ Variable in text: ${var}iable """) print 'TEMPLATE:', t.substitute(values) s=""" Variable : %(var)ss Escape : %% Variable in text: %(var)sssssiable """ print 'INTERPOLATION:', s%values
import re print '-'*30 #about regular expression search() pattern = 'this' text='Does this text match the pattern?' match = re.search(pattern, text) s=match.start() e=match.end() print 'Dound "%s" \nin "%s" \nfrom %d to %d ("%s")' % (match.re.pattern,match.string,s,e,text[s:e]) #start()和end()方法可以给出字符串中相应的索引。
print '-'*30 #about the Compile() regexes=[re.compile(p) for p in ['this','that'] ] text='Does this text match the pattern?' print 'Text: %r\n' % text for regex in regexes: print 'seeking "%s" ->' % regex.pattern if regex.search(text): print 'match!' else: print 'no match!'
print '-'*30 #about the findall() text = 'bbbbbababbababbabbbaba' pattern = 'ba' for match in re.findall(pattern, text): print match print '-'*30 #about the finditer() #finditer会返回一个迭代器,可以生成match实例,而不像findall()是直接返回的字符串。 text='aaaadaaaaadadadada' pattern='da' for match in re.finditer(pattern,text): s=match.start() e=match.end() print 'Found "%s" at %d:%d' % (text[s:e],s,e)
print '-'*30 #一种iterall()的不太高效的实现方式。 text='this is some text -- with punctuation.' pattern=re.compile(r'\b\w*is\w*\b') print 'text:', text pos=0 while True: match=pattern.search(text,pos) print match if not match: break s=match.start() e=match.end() print s,e print '%d: %d = "%s"' % (s,e-1,text[s:e]) pos=e
原文地址:http://blog.csdn.net/ling1510/article/details/40380269