问题描述
利用re.sub()完成字符串匹配和切割任务,如: 输入:
- 由AGCT组成的DNA序列(字符串)s,如:‘GCATAGTAATGTATTAATGGC’
- 切割酶的切割pattern, 并使用"|“表示切割,如” A.T|AAT”
输出: 切割结果,如 [GCATAGT; AATGTATT; AATGGC]
求解
使用下面一行代码即可求解:
re.sub(pattern, r'\1:\2' s).split(':')
原理
根据如下代码和注释理解re.sub即可。
import re
pattern = r'(.*)cat(.*)aa'
replacement_template = r'\2cat\1'
replacement_template = r'\1cat\2'
replacement_template = r'\2'
text = 'dogcatllama'
new_text = re.sub(pattern, replacement_template, text)
print(text, '=>', new_text)
phone = "2004-959-559 # 这是一个电话号码"
num = re.sub(r'#.*$', "", phone)
print ("电话号码 : ", num)
num = re.sub(r'\D', "", phone)
print ("电话号码 : ", num)
pattern = '[0-9]+'
string = 'Account Number - 12345, Amount - 586.32'
repl = 'NN'
print('Original string')
print(string)
result = re.sub(pattern, repl, string)
print('After replacement')
print(result)
pattern = '[0-9]+'
string = 'Account Number - 12345, Amount - 586.32'
repl = 'NN'
print('Original string')
print(string)
result = re.sub(pattern, repl, string, count=2)
print('After replacement')
print(result)
pattern = '[a-z]+'
string = 'Account Number - 12345, Amount - 586.32'
repl = 'AA'
print('Original string')
print(string)
result = re.sub(pattern, repl, string, flags=re.IGNORECASE)
print('After replacement')
print(result)
|