python 字符串替换

字符串替换可以用内置的方法和正则表达式完成。 1用字符串本身的replace方法:

a = 'hello word'
b = a.replace('word','python')
print b

2用正则表达式来完成替换:

import re
a = 'hello word'
strinfo = re.compile('word')
b = strinfo.sub('python',a)
print b
3 单字符多次替换
import re
astr = 'AGTCTTAGGC'
charmap = {'A':'T','T':'A','C':'G','G':'C'}
new = re.sub(r'[ATCG]', lambda x: charmap[x.group(0)], astr)
print(new)
原文地址:https://www.cnblogs.com/wipy/p/4171151.html