一次完成多个替换:import re def multiple_replace(text,adict): rx=re.compile("|".join(map(re.escape,adict))) def one_xlat(match): return adict[match.group(0)] return rx.sub(one_xlat,text) def make_xlat(*arge,**kwds): adict=dict(*arge,**kwds) rx=re.compile("|".join(map(re.escape,adict))) def one_xlat(match): return adict[match.group(0)] def xlat(text): return rx.sub(one_xlat,text) return xlat if __name__=="__main__": text="larry wall is the creator of perl" adict={ "larry wall":"guido van rossum", "creator":"brnevolent dictator for life", "perl":"python", } print multiple_replace(text,adict) translate=make_xlat(adict) print translate(text)
结果:
guido van rossum is the brnevolent dictator for life of python guido van rossum is the brnevolent dictator for life of python
15页 检查字符串是否包含某字符集合的字符
for if 循环 itertools.ifilter defference containsALL symmetric_difference translate string.maketrans
import stringmsg=string.Template('the square of $number is $square')for number in range(10): square=number*number print msg.substitute(locals())for i in range(10): print msg.substitute(number=i,square=i*i)
for number in range(10): print msg.substitute(locals(),square=number*number)
将所有变量传递到本地
the square of 0 is 0
the square of 1 is 1
the square of 2 is 4
the square of 3 is 9
the square of 4 is 16
the square of 5 is 25
the square of 6 is 36
the square of 7 is 49
the square of 8 is 64
the square of 9 is 81
11
最新推荐文章于 2023-11-01 17:01:33 发布